Immutable.js Iterables offer the Reduce () method, a powerful and often misunderstood functional operator on which map (), F Ilter (), groupBy (), etc. is built. The concept is simple:reduce transforms your iterable to something else, that's all. The name is misleading as the actually "reduce" anything. Let's replicate the GroupBy () and filter () methods with reduce to illustrate how it works.
Assume you has a list to Todos and each todo with a "completed" Prop:
GroupBy () Like:
Const TODOS =Immutable.list ([{ID:1, Title:"Immutable.js", Completed:true}, {ID:2, Title:"RxJS", Completed:false}, {ID:3, Title:"Reactjs", Completed:false}]); const Groupedtodos= Todos.reduce (ACC, curr) = ={let key= curr.completed? "Completed": "Incompleted"; //Initial value is a immutable Map object, so use Get ("completed") to get the Immutable.list () and then push the Curr Val UE into ITLet list =Acc.get (key). push (Curr); //immutable return a new list from last push, so we need to set this list to the initial value returnacc.set (key, list); }, Immutable.map ({"Completed": Immutable.list (), "incompleted": Immutable.list ()})); Console.log (Groupedtodos.get ("incompleted"). Get (1). title);//"Reactjs"
Filter () Like:
// Get all imcompleted todosconst FILTEREDTODOS = Todos.reduce ((ACC, curr) += {if(! curr.completed) { = Acc.push (curr); } return acc;}, Immutable.list ()); Console.log (Filteredtodos.get (// "Reactjs"
[Immutable.js] Transforming immutable Data with Reduce