More Examples for Reduce

Friday, March 10th 2023

Here are some more examples of using the .reduce() function in smart ways with JavaScript:

  1. Finding the maximum value in an array:
const numbers = [1, 5, 2, 9, 3]; const max = numbers.reduce((prev, current) => Math.max(prev, current)); console.log(max); // 9
  1. Flattening an array of arrays:
const nested = [[1, 2], [3, 4], [5, 6]]; const flattened = nested.reduce((prev, current) => prev.concat(current)); console.log(flattened); // [1, 2, 3, 4, 5, 6]
  1. Counting occurrences of values in an array:
const words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']; const counts = words.reduce((prev, current) => { prev[current] = (prev[current] || 0) + 1; return prev; }, {}); console.log(counts); // { apple: 3, banana: 2, cherry: 1 }
  1. Removing duplicates from an array:
const numbers = [1, 2, 3, 2, 1, 4, 5]; const unique = numbers.reduce((prev, current) => { if (!prev.includes(current)) { prev.push(current); } return prev; }, []); console.log(unique); // [1, 2, 3, 4, 5]
  1. Grouping objects by a property:
const people = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, { name: 'Dave', age: 30 } ]; const groups = people.reduce((prev, current) => { const key = current.age; if (!prev[key]) { prev[key] = []; } prev[key].push(current.name); return prev; }, {}); console.log(groups); /* { 25: ['Alice', 'Charlie'], 30: ['Bob', 'Dave'] } */

These are just a few more examples of the many ways in which the .reduce() function can be used in JavaScript. It's a very versatile method that can help you solve many different problems.