Power of reduce – Swiss army knife of functional JavaScript

Today, we will see a powerful use of reduce function provided by JavaScript. In this example, we are provided with a mixed array of numbers, string, and objects. What we wish to achieve is a summary output array containing only three members:

  • sum of numbers in the input array
  • single string containing all strings in input array concatenated with space
  • single object containing all the object members (key-value pairs) of objects in the input array

The reduce function here makes use of ‘typeof’ and ternary operators to do the right operations (could be possibly replaced by individual filters).

 

let input = [
  1,
  2,
  3,
  { a: 'Apple', b: 'Bag' },
  5,
  6,
  'hello',
  { 1: 'One', 2: 'Two' },
  'world'
];
//op = [sum of number, string concatenated with space, single object with all keys]
let op = [0, '', {}];
op = input.reduce((prev, curr) => {
  typeof curr === 'number'
    ? (prev[0] = prev[0] + curr)
    : typeof curr === 'string'
      ? (prev[1] = prev[1] + ' ' + curr)
      : (prev[2] = { ...prev[2], ...curr });
  return prev;
}, op);
console.log(op);
//[ 17,
//  ' hello world',
//  { '1': 'One', '2': 'Two', a: 'Apple', b: 'Bag' } ]

 

Leave a Reply