Home >Web Front-end >JS Tutorial >Comprehensive Guide to JavaScript `reduce()` Method with Real-Life Examples
The reduce() method is a powerful array method in JavaScript, used to iterate through an array and reduce it to a single value. This method is versatile and can handle operations like summing numbers, flattening arrays, creating objects, and more.
array.reduce(callback, initialValue);
Suppose you have a shopping cart, and you want to calculate the total price of the items.
const cart = [ { item: "Laptop", price: 1200 }, { item: "Phone", price: 800 }, { item: "Headphones", price: 150 } ]; const totalPrice = cart.reduce((acc, curr) => acc + curr.price, 0); console.log(`Total Price: $${totalPrice}`); // Total Price: 50
You want to group items by their category.
const inventory = [ { name: "Apple", category: "Fruits" }, { name: "Carrot", category: "Vegetables" }, { name: "Banana", category: "Fruits" }, { name: "Spinach", category: "Vegetables" } ]; const groupedItems = inventory.reduce((acc, curr) => { if (!acc[curr.category]) { acc[curr.category] = []; } acc[curr.category].push(curr.name); return acc; }, {}); console.log(groupedItems); /* { Fruits: ['Apple', 'Banana'], Vegetables: ['Carrot', 'Spinach'] } */
You receive data from different departments as nested arrays and need to combine them into one.
const departmentData = [ ["John", "Doe"], ["Jane", "Smith"], ["Emily", "Davis"] ]; const flattenedData = departmentData.reduce((acc, curr) => acc.concat(curr), []); console.log(flattenedData); // ['John', 'Doe', 'Jane', 'Smith', 'Emily', 'Davis']
You have an array of website page views and want to count how many times each page was visited.
const pageViews = ["home", "about", "home", "contact", "home", "about"]; const viewCounts = pageViews.reduce((acc, page) => { acc[page] = (acc[page] || 0) + 1; return acc; }, {}); console.log(viewCounts); /* { home: 3, about: 2, contact: 1 } */
The reduce() method can mimic the functionality of map().
const numbers = [1, 2, 3, 4]; const doubled = numbers.reduce((acc, curr) => { acc.push(curr * 2); return acc; }, []); console.log(doubled); // [2, 4, 6, 8]
You want to find the highest sales figure from a dataset.
const sales = [500, 1200, 300, 800]; const highestSale = sales.reduce((max, curr) => (curr > max ? curr : max), 0); console.log(`Highest Sale: $${highestSale}`); // Highest Sale: 00
You receive an array of user data and need to convert it into an object keyed by user ID.
array.reduce(callback, initialValue);
The reduce() method is incredibly versatile and can be adapted for a variety of tasks, from summing values to transforming data structures. Practice with real-life examples like these to deepen your understanding and unlock the full potential of reduce() in your JavaScript projects.
The above is the detailed content of Comprehensive Guide to JavaScript `reduce()` Method with Real-Life Examples. For more information, please follow other related articles on the PHP Chinese website!