Transform an array into any datatype with reduce()

JS
S
JavaScript

Use cases: Provided an array, return a number, object, string, boolean, any.. Some examples of using reduce() for iterating, counting and looping. Can be used as an alternative to: map, filter, reject, groupBy, indexBy.

1// Converting an array of objects to an object
2Object.assign({}, ...peopleArray.map(person => ({[person.id]: person})))
3
4
5/* 
6    .reduce(functionToRun, startingData)
7    functionToRun(starterElement, currentElement)
8*/
9// Count telemetry and process items
10const measures = [ {type:"telemetry", val: 2}, {type:"cpu", val: 100}, {type:"memory", val: 88}, {type:"telemetry", val: 12} ];
11const starterStructure = {telemetry: 0, process: 0};
12const countedResults = measures.reduce((starter, measure) => {
13    // modify starter
14    measure.type === 'telemetry' ? starter.telemetry++ : starter.process++;
15    return starter; //modified starter
16},starterStructure);
17
18// Sum elements
19const arr = [1,2,3,4];
20
21// On each iteration, add the current value to the accumulator and return it
22const sum = arr.reduce((acc, val) => {
23  return acc + val;
24});
25
26// Count elements
27const count = arr.reduce((acc, val) => {
28 return acc + 1;    
29});
30
31// Sum with an initial value of 10
32const sum1 = arr.reduce((acc, val) => {
33  return acc + val;
34}, 10);
35
36
37const balances = [
38  {
39    invoice: 'PT1',
40    balance: 10,
41  },
42  {
43    invoice: 'PT2',
44    balance: 16,
45  },  
46  {
47    invoice: 'PT3',
48    balance: -5,
49  }
50];
51
52// Count all negative balances
53const negativeBalancesCount = balances.reduce((acc,val) => {
54   if(val.balance < 0){
55     return acc + 1;
56   } else {
57    return acc;
58  }
59},0);
60
61// Count all positive balances
62const positiveBalancesCount = balances.reduce((acc,val) => {
63   if(val.balance > 0){
64     return acc + 1;
65   } else {
66    return acc;
67  }
68},0);
69
70// Count all negative balances with filter and reduce
71const shorterNegativeBalanceCount = balances
72  .filter(val => val.balance < 0)
73  .reduce((acc,val) => acc + 1, 0)

Created on 11/20/2017