Array Methods
Array methods let you process a whole list with one clear line instead of a hand-written loop. You pass each method a small function (a callback) that says what to do with one item, and the method does the looping. map, filter and reduce are the stars, but forEach, find, some, every and sort are just as useful.
How callbacks work here
Each of these methods calls your callback once per item, passing up to three arguments: the item, its index and the whole array. Usually you only need the first, and an arrow function keeps it short.
forEach: do something with each item
const names = ["Amani", "Baraka", "Chiku"];
names.forEach((name, index) => {
console.log(`${index + 1}. ${name}`);
});
forEach always returns undefined; it is for side effects such as printing or updating the page. Unlike a for loop, you can't break out of it.
map, filter and reduce
These three return new values and never change the original array.
maptransforms every item and returns a new array of the same length.filterkeeps only the items for which the callback returns a truthy value.reducecombines all items into a single value, carrying an accumulator from one step to the next.
const prices = [120, 45, 300, 80]; const withDelivery = prices.map(p => p + 50); const affordable = prices.filter(p => p <= 100); const total = prices.reduce((sum, p) => sum + p, 0); console.log(withDelivery); console.log(affordable); console.log(total); console.log(prices);
map returns one new item for every old item, filter returns only the items that pass, and reduce walks the list carrying a running result.In reduce((sum, p) => sum + p, 0), the 0 is the initial value of the accumulator sum. Whatever the callback returns becomes sum for the next item, and the final return is the answer.
With braces, an arrow needs return. prices.map(p => { p * 2 }) gives [undefined, undefined, undefined, undefined]. Also always pass an initial value to reduce: on an empty array without one, it throws TypeError: Reduce of empty array with no initial value.
Chaining methods
Because map and filter return arrays, you can chain them into a readable pipeline:
const prices = [120, 45, 300, 80]; const result = prices .filter(p => p >= 80) // [120, 300, 80] .map(p => p * 2) // [240, 600, 160] .reduce((sum, p) => sum + p, 0); console.log(result);
find, findIndex, some and every
const students = [
{ name: "Amina", score: 72 },
{ name: "Brian", score: 48 },
{ name: "Chebet", score: 91 }
];
const best = students.find(s => s.score > 90);
console.log(best.name);
console.log(students.findIndex(s => s.name === "Brian"));
console.log(students.some(s => s.score < 50));
console.log(students.every(s => s.score >= 40));
console.log(students.find(s => s.score > 95));
find returns the first item that matches (or undefined), and findIndex its index (or -1). some asks "does at least one match?" and every asks "do all match?". All four stop as soon as they know the answer.
sort: careful with numbers
By default sort() converts items to strings and sorts them alphabetically, character by character. For words that is fine; for numbers it is wrong:
const nums = [10, 9, 1, 100, 25]; console.log(nums.toSorted()); console.log(nums.toSorted((a, b) => a - b)); console.log(nums.toSorted((a, b) => b - a)); console.log(nums);
As strings, "100" comes before "25" because "1" is less than "2". Fix it with a compare function: it receives two items and returns a negative number if a should come first, a positive number if b should, or 0 to keep their order. a - b sorts ascending; b - a sorts descending.
The older sort() takes the same compare function but changes the original array (and returns it). toSorted(), added in ES2023, returns a sorted copy and leaves the original alone, as the last line shows. Sorting objects works the same way: students.toSorted((a, b) => b.score - a.score) puts the highest score first. For words with mixed capitals, compare with localeCompare: words.toSorted((a, b) => a.localeCompare(b)), since plain sort() puts every capital letter before every lower-case one.
Try it: a marks report
const marks = [56, 89, 72, 40, 95];
const passed = marks.filter(m => m >= 50);
const curved = passed.map(m => m + 5);
const average = curved.reduce((sum, m) => sum + m, 0) / curved.length;
console.log("Passed:", passed.join(", "));
console.log("Curved:", curved.join(", "));
console.log("Average:", average);
console.log("Sorted:", marks.toSorted((a, b) => a - b).join(", "));
The four curved marks add up to 332, and 332 / 4 is 83. Try changing the pass mark or the curve and run it again.
Key points
- Array methods take a callback that receives each item (and its index).
forEachis for side effects;maptransforms,filterselects,reducecombines, and none of them change the original.find/findIndexlocate the first match;some/everyanswer yes-or-no questions.sort()compares as strings by default and mutates; use(a, b) => a - bfor numbers andtoSorted()for a copy.
Tip: use the ← and → keys to move between pages.
