Array Methods — JavaScript

Array methods run a callback (a function you pass to the method) for every item of the array. filter keeps the items whose callback result is true. map…

Out of six dishes on a menu, you only want the ones whose name starts with S. With a loop, that takes four steps: make an empty array, go through every item, check its first letter, then push the items that match. That is a lot for such a small job, and you will write it again every time you need to filter.

Arrays have built-in methods for working on all their items at once: filtering them, changing them, finding one, or combining them all into a single value. You only write what to do with one item. The method repeats it for every item, so you don't have to write the loop yourself.

filter: keep the items that pass

This example filters an array of foods and keeps the ones whose name starts with S:

const foods = ["Fried Rice", "Beef Curry", "Salad", "Noodles", "Meatballs", "Soup"];

const result = foods.filter((food) => food.startsWith("S"));

console.log(result); // ["Salad", "Soup"]
console.log(foods); // still all 6 foods

A function that you pass to a method, like the arrow function in this example, is called a callback. filter doesn't change the original array. It makes a new one. So store the new array in a variable, or return it right away with return. Otherwise it is lost.

In the exercise, you filter even numbers with %. The % sign gives the remainder of a division: 7 % 2 is 1, and 8 % 2 is 0. An even number leaves a remainder of 0 when divided by 2, so the condition for an even number is n % 2 === 0.

map: change every item

This example halves every price:

const prices = [10, 25, 5];

const halves = prices.map((p) => p / 2);

console.log(halves); // [5, 12.5, 2.5]

map runs the callback for every item. The value the callback returns becomes an item of the new array. The new array always has the same number of items as the original.

Guess first: what does [1, 2, 3].map((n) => { n * 2 }) give?

It gives [undefined, undefined, undefined], not [2, 4, 6]. The cause is the curly braces: a callback that uses { } returns nothing when there is no return. Write (n) => n * 2 or (n) => { return n * 2; }.

find: take the first one that matches

This example looks for a city whose name starts with S, then for one that starts with Z:

const cities = ["Leeds", "Sheffield", "Swindon", "Manchester"];

console.log(cities.find((c) => c.startsWith("S"))); // Sheffield
console.log(cities.find((c) => c.startsWith("Z"))); // undefined

find stops at the first item whose callback result is true, and returns that item itself, not an array. That is why the first search gives only Sheffield, although Swindon starts with S too. If nothing matches, the result is undefined.

reduce: combine the items into one value

This example adds up four numbers into one total:

const numbers = [1, 2, 3, 4];

const total = numbers.reduce((acc, n) => acc + n, 0);

console.log(total); // 10

A real example: a shopping cart. In an app, the items of an array are usually objects. In this code, the parameter item holds one object of the cart. item.price reads the price property of that object:

const cart = [
  { name: "Rice", price: 30, quantity: 1 },
  { name: "Eggs", price: 2, quantity: 10 },
];

const total = cart.reduce((acc, item) => acc + item.price * item.quantity, 0);
console.log(total); // 50

const pricey = cart.filter((item) => item.price > 10).map((item) => item.name);
console.log(pricey); // ["Rice"]

reduce adds up price × quantity for each object: 30 × 1 + 2 × 10 = 50.

The pricey line chains two methods. filter gives a new array with the objects whose price is more than 10. Then map runs on that new array and takes the name of each object.

Other options besides the four methods above:

Method When to use it
some / every You only need true or false: at least one item matches (some), or every item matches (every).
findIndex You need the position, not the item. It gives -1 when nothing matches.
toSorted Sorts like sort (below), but does not change the original array.

⚠️ Methods that don't give what you'd expect

🔬 Try it yourself

Pick a method and see what the callback returns for each item.

TL;DR: Array methods run a callback (a function you pass to the method) for every item of the array. filter keeps the items whose callback result is true. map replaces each item with the callback's result, so the number of items stays the same. find takes the first item that matches. reduce((acc, n) => ..., 0) combines every item into one value: acc holds the result so far and starts at 0. filter and map make a new array, so store the result in a variable or return it with return. A callback that uses { } needs return. The condition for even numbers: n % 2 === 0 (% gives the remainder of a division).

⚡ filter: keep what passes

Write:

const result = foods.filter((food) => food.startsWith("S"));
// ["Salad", "Soup"]

Meaning: filter runs the callback (the function in its parentheses) for every item of the array foods, a list of food names. Here the callback checks whether a food's name starts with S. Items that give true go into a new array, and items that give false are left out. The original array doesn't change, so store the new array in a variable or return it right away with return.

⚡ map: change every item

Write:

const prices = [10, 25, 5];

const halves = prices.map((p) => p / 2);
// [5, 12.5, 2.5]
Guess first: what does [1, 2, 3].map((n) => { n * 2 }) give?

[undefined, undefined, undefined]. A callback that uses { } returns nothing when there is no return.

Meaning: map runs the callback for every item. The value the callback returns becomes an item of the new array. The new array always has the same number of items as the original.

⚡ reduce: combine the items into one value

Write:

const total = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0);
// 10

Meaning: reduce runs the callback for every item and combines them all into one value. acc holds the result so far, and n is the item being processed. The 0 at the end is the starting value of acc. On every pass, the callback's result becomes the next acc: 0 + 1, then 1 + 2, and so on up to 10.

What you will learn