Reduce in Javascript
The reduce() method is one of the most powerful array methods. It executes a reducer function on each element, resulting in a single output value.
Key Concepts
- Transforms array into single value
- Very flexible - can return any data type
- Great for calculations and aggregations
- Can flatten arrays and group data
Sum of Array
Code
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => { return accumulator + currentValue; }, 0); console.log(sum); // 15 const sum2 = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum2); // 15
Product of Array
Code
const product = numbers.reduce((acc, curr) => acc * curr, 1); console.log(product); // 120
Find Maximum Value
Code
const max = numbers.reduce((acc, curr) => { return curr > acc ? curr : acc; }, numbers[0]); console.log(max); // 5 const max2 = numbers.reduce((acc, curr) => Math.max(acc, curr)); console.log(max2); // 5
Flatten Array
Modern approach.
Code
const nested = [[1, 2], [3, 4], [5, 6]]; const flattened = nested.reduce((acc, curr) => { return acc.concat(curr); }, []); console.log(flattened); // [1, 2, 3, 4, 5, 6] const flattened2 = nested.reduce((acc, curr) => [...acc, ...curr], []); console.log(flattened2); // [1, 2, 3, 4, 5, 6]
Count Occurrences
Code
const fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]; const count = fruits.reduce((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1; return acc; }, {}); console.log(count); // { apple: 3, banana: 2, orange: 1 }
Group by Property
Mumbai: [{ name: "Kuldeep",.
}, { name: "Suresh",.
}], Delhi: [{ name: "Ramesh",.
}, { name: "Rajesh",.
Code
const people = [ { name: "Kuldeep", age: 25, city: "Mumbai" }, { name: "Ramesh", age: 30, city: "Delhi" }, { name: "Suresh", age: 25, city: "Mumbai" }, { name: "Rajesh", age: 30, city: "Delhi" } ]; const groupedByCity = people.reduce((acc, person) => { const city = person.city; if (!acc[city]) { acc[city] = []; } acc[city].push(person); return acc; }, {}); console.log(groupedByCity);
Transform Array to Object
1: { id: 1, name: "Laptop", price: 50000 }, 2: { id: 2, name: "Phone", price: 30000 }, 3: { id: 3, name: "Tablet", price: 25000 }.
Code
const items = [ { id: 1, name: "Laptop", price: 50000 }, { id: 2, name: "Phone", price: 30000 }, { id: 3, name: "Tablet", price: 25000 } ]; const itemsMap = items.reduce((acc, item) => { acc[item.id] = item; return acc; }, {}); console.log(itemsMap);
Remove Duplicates
Code
const duplicates = [1, 2, 2, 3, 3, 3, 4, 5, 5]; const unique = duplicates.reduce((acc, curr) => { if (!acc.includes(curr)) { acc.push(curr); } return acc; }, []); console.log(unique); // [1, 2, 3, 4, 5]
Pipeline/Compose Functions
Code
const add = x => x + 1; const multiply = x => x * 2; const subtract = x => x - 3; const functions = [add, multiply, subtract]; const result = functions.reduce((acc, fn) => fn(acc), 5); console.log(result); // ((5 + 1) * 2) - 3 = 9
Chaining with Other Methods
Calculate average score per person [{ name: "Kuldeep", average: 82.
5 }, { name: "Ramesh", average: 92.
Code
const data = [ { name: "Kuldeep", score: 85, subject: "Math" }, { name: "Ramesh", score: 90, subject: "Math" }, { name: "Kuldeep", score: 80, subject: "Science" }, { name: "Ramesh", score: 95, subject: "Science" } ]; const avgScores = data.reduce((acc, item) => { if (!acc[item.name]) { acc[item.name] = { total: 0, count: 0 }; } acc[item.name].total += item.score; acc[item.name].count += 1; return acc; }, {}); const averages = Object.entries(avgScores).map(([name, data]) => ({ name, average: data.total / data.count })); console.log(averages);
Custom Reduce Implementation
Common Use Cases 1.
Sum all values 2.
Flatten nested arrays 3.
Create lookup map 4.
Compose functions.
Code
Array.prototype.myReduce = function(callback, initialValue) { let accumulator = initialValue !== undefined ? initialValue : this[0]; let startIndex = initialValue !== undefined ? 0 : 1; for (let i = startIndex; i < this.length; i++) { accumulator = callback(accumulator, this[i], i, this); } return accumulator; }; const test = [1, 2, 3, 4, 5].myReduce((acc, curr) => acc + curr, 0); console.log(test); // 15 const sum3 = [1, 2, 3].reduce((a, b) => a + b, 0); const flat = [[1, 2], [3, 4]].reduce((a, b) => a.concat(b), []); const map = [{ id: 1, name: "A" }, { id: 2, name: "B" }] .reduce((acc, item) => ({ ...acc, [item.id]: item }), {}); const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
Summary
Understanding reduce is essential for mastering javascript. Practice these examples and experiment with variations to deepen your understanding.
Key Takeaways
- reduce is a fundamental concept in javascript
- Practice with these examples to build confidence
- Experiment with variations to explore edge cases
- Understanding reduce will help you in technical interviews