Learn to transform, filter, and aggregate data with the four array methods most used in real-world projects.
Open this lesson in KodokonIn a real project, you spend your time transforming data: a list of products to display, API results to sort, a cart to total up. The map, filter, reduce, and find methods replace most of your for loops with shorter, more expressive code. They never modify the original array: they return a new result, which prevents a whole class of bugs.
const products = [
{ name: "keyboard", price: 49, inStock: true },
{ name: "mouse", price: 25, inStock: false },
{ name: "screen", price: 199, inStock: true }
];
const names = products.map((product) => product.name);
console.log(names); // ["keyboard", "mouse", "screen"]filter keeps only the elements that pass a test and returns a new array, possibly empty. find stops at the first matching element and returns the element itself, or undefined if nothing matches. Mental exercise: to get all the products in stock, which one do you pick? And to get the product named "mouse"?
const available = products.filter((p) => p.inStock);
console.log(available.length); // 2
const mouse = products.find((p) => p.name === "mouse");
console.log(mouse.price); // 25reduce is the most powerful: it reduces an array to a single value (a number, an object, a string). It takes a function with an accumulator and the current element, plus an initial value. Classic use case: computing a cart total.
const cart = [
{ label: "T-shirt", quantity: 2, unitPrice: 15 },
{ label: "Cap", quantity: 1, unitPrice: 12 }
];
const total = cart.reduce(
(sum, item) => sum + item.quantity * item.unitPrice,
0
);
console.log(total); // 42To pick the right method, ask yourself one question: what shape should the result have? As many elements as the original but transformed: map. A subset: filter. A single element: find. A single computed value: reduce. This reflex will save you precious time in interviews and on projects alike.
find return if no element satisfies the condition?cart.reduce((sum, item) => sum + item.unitPrice, 0), what is the final 0 for?