DEV Community

Marco Pestrin
Marco Pestrin

Posted on • Edited on

2 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more