DEV Community

Marco Pestrin
Marco Pestrin

Posted on • Updated on

3 ways to use reduce in javascript

  • Flat an array
let arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
const flattened = arr.reduce((acc, item) => [...acc, ...item], []);
console.log(flattened);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen mode Exit fullscreen mode

If you have a more complex array there is this other solution

arr = [
  [1, 2, 3],
  [4, ["a", [5]], 6],
  [7, 8, [9, 10]],
];
const flatten = (arr) => arr.reduce((acc, item) => {
  if (item instanceof Array) {
    return acc.concat(flatten(item))
  }
  acc.push(item);
  return acc;
}, []);
flatten(arr);
Enter fullscreen mode Exit fullscreen mode
  • Sum all numbers
arr = [4, 5, 9, 18];
const total = arr.reduce((acc, number) => acc + number, 0);
console.log(total);
// 36
Enter fullscreen mode Exit fullscreen mode
  • Change in an object with the number of occurrences
arr = ["Los Angeles", "London", "Amsterdam", "Singapore", "London", "Tokyo", "Singapore"];
const counter = arr.reduce((acc, city) => {
  acc[city] = acc[city] ? acc[city] + 1 : 1;
  return acc;
}, {});
console.log(counter);
/*
{
  "Los Angeles": 1,
  "London": 2,
  "Amsterdam": 1,
  "Singapore": 2,
  "Tokyo": 1
}
*/
Enter fullscreen mode Exit fullscreen mode

Top comments (0)