Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 20, 2022 03:51 pm GMT

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]

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);
  • Sum all numbers
arr = [4, 5, 9, 18];const total = arr.reduce((acc, number) => acc + number, 0);console.log(total);// 36
  • 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}*/

Original Link: https://dev.to/pestrinmarco/3-ways-to-use-reduce-in-javascript-1442

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To