Here are some more examples of using the .reduce()
function in smart ways with JavaScript:
const numbers = [1, 5, 2, 9, 3]; const max = numbers.reduce((prev, current) => Math.max(prev, current)); console.log(max); // 9
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]
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 }
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]
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.