repl.it
@brnkrygs/

Exploring Reduce

Nodejs

Exploring Reduce

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const result = [1,2,3,4].reduce(( sum, item ) => sum+=item, 0 );

console.log( 'result:', result );

const products = [
  { id: 1, category: 'fruit', name: 'Apple' },
  { id: 2, category: 'vegetable', name: 'Carrot' },
  { id: 3, category: 'grain', name: 'Oats' },
  { id: 4, category: 'fruit', name: 'Pear' },
];

const categorizedProducts = products
  .reduce(( currentCollection, item ) => {

    // Check if we have this key or not. If not, initialize a child array
    if( !currentCollection[item.category]){
      currentCollection[item.category] = [];
    }

    // Collect this item under the right category
    currentCollection[item.category].push( item );

    // Continue building on this collection
    return currentCollection;
  }, {});


console.log( 'categorized products:' );
console.log( JSON.stringify( categorizedProducts ));