JavaScript Array Methods

Transform, filter, search, sort and total arrays in one readable line.

Lesson 24 of 56Intermediate14 min read

Loops work, but modern JavaScript has a neater way to handle lists: array methods that take a function and apply it to each item for you. Want every price with tax added? Use map. Only the cheap items? Use filter. The total? Use reduce. Your code becomes shorter and easier to read.

Each array method answers one specific question about a list, and its name tells the reader which question that is. A filter call clearly keeps some items and drops others, whereas a for loop could be doing anything until you read every line. That clarity is why array methods are used so heavily in modern code.

map, filter and reduce

MethodQuestion it answersReturns
map(fn)"What does each item become?"A new array of the same length
filter(fn)"Which items should I keep?"A new array, possibly shorter
reduce(fn, start)"What single value do they combine into?"One value

None of these change the original array. They return something new, so store the result in a variable.

reduce is the hardest of the three at first. Think of it as carrying a running total: (sum, n) => sum + n takes the total so far and the next item, and returns the new total. The second argument, often 0, is the starting value.

Searching and checking with find, some and every

MethodReturns
find(fn)The first item for which fn returns true, or undefined
findIndex(fn)That item's index, or -1
some(fn)true if at least one item passes
every(fn)true if all items pass
includes(x)true if that exact value is in the array

Use find when you need the item itself, such as the product with a particular id, and some or every when you only need a yes or no answer.

Looping and sorting

  • forEach(fn) runs code for each item and returns nothing. Use it for side effects, such as logging or updating the page.
  • sort(compareFn) sorts the array in place, changing the original. Numbers need a compare function: (a, b) => a - b sorts from low to high and (a, b) => b - a from high to low.
  • toSorted() works like sort but returns a sorted copy and leaves the original alone.
  • flat() flattens nested arrays into a single level.

Without a compare function, sort compares items as text, which is why [10, 9, 1].sort() gives [1, 10, 9].

The callback's arguments

Each method calls your function with three arguments: (item, index, array). Most of the time you only need item, but index is useful for numbering, as in items.map((item, i) => ${i + 1}. ${item}).

JavaScript Array Methods Syntax

Array method shapes

arr.map(item => newValue);
arr.filter(item => trueOrFalse);
arr.find(item => trueOrFalse);
arr.reduce((acc, item) => newAcc, startValue);
arr.forEach(item => { /* do something */ });
arr.toSorted((a, b) => a - b);

JavaScript Array Methods Summary

  • Array methods take a function and apply it to every item.
  • map transforms, filter selects and reduce combines into one value.
  • find, some and every search and check items.
  • sort changes the original array; toSorted returns a copy.
  • Chain methods to process data step by step.

JavaScript Array Methods Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

map and filter

const temps = [12, 25, 31, 8, 19];

const fahrenheit = temps.map(c => c * 9 / 5 + 32);
const warmDays = temps.filter(c => c >= 20);
const labels = temps.map((c, i) => `Day ${i + 1}: ${c}°C`);

console.log(fahrenheit);
console.log(warmDays);
console.log(labels);
console.log(temps);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 3Every temperature is converted, and there are still 5 items.
  2. Line 4Keep only temperatures of 20 or more.
  3. Line 5The second argument is the index.
  4. Line 10The original array is unchanged.
Example 2

Working with arrays of objects

Real data usually looks like this.

const products = [
  { name: "Notebook", price: 4, inStock: true },
  { name: "Backpack", price: 35, inStock: false },
  { name: "Pen set", price: 9, inStock: true },
  { name: "Lamp", price: 22, inStock: true },
];

const names = products.map(p => p.name);
const available = products.filter(p => p.inStock);
const lamp = products.find(p => p.name === "Lamp");
const anyCheap = products.some(p => p.price < 5);
const allInStock = products.every(p => p.inStock);
const total = available.reduce((sum, p) => sum + p.price, 0);

console.log(names);
console.log(available.length, "available");
console.log(lamp);
console.log(anyCheap, allInStock);
console.log("Total of available:", total);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 8Pull out one property from every object.
  2. Line 9Keep the ones in stock.
  3. Line 10The first object whose name is "Lamp".
  4. Lines 11 to 12Is any item under £5? Are all in stock?
  5. Line 13Add up prices: start at 0, add each price to the running sum.
Example 3

Sorting and chaining

const scores = [
  { player: "Ava", points: 82 },
  { player: "Ben", points: 95 },
  { player: "Cy", points: 67 },
];

const leaderboard = scores.toSorted((a, b) => b.points - a.points);

leaderboard.forEach((s, i) => {
  console.log(`${i + 1}. ${s.player}: ${s.points}`);
});

const average = scores
  .map(s => s.points)
  .reduce((sum, p) => sum + p, 0) / scores.length;
console.log("Average:", average.toFixed(1));

console.log([10, 9, 1].sort());
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 7Sorted copy, highest points first.
  2. Lines 9 to 11forEach to print each row.
  3. Lines 13 to 15Chain: get the points, add them up, divide.
  4. Line 18Careful! Without a compare function, sort compares as strings: [1, 10, 9].

Common JavaScript Array Methods Mistakes

Forgetting to return in a callback

Don't
const doubled = [1, 2, 3].map(n => { n * 2 }); // [undefined, undefined, undefined]
Do
const doubled = [1, 2, 3].map(n => n * 2);

Using forEach when you want a new array

Don't
const names = users.forEach(u => u.name); // undefined
Do
const names = users.map(u => u.name);

forEach always returns undefined.

Sorting numbers without a compare function

Don't
[40, 100, 5].sort(); // [100, 40, 5]
Do
[40, 100, 5].sort((a, b) => a - b); // [5, 40, 100]

JavaScript Array Methods in Real Projects

Data in, interface out

Most front-end work is exactly this: an API gives you an array of objects, you filter by what the user searched, toSorted by price, map each one into HTML, and reduce to show a total. React apps render lists with items.map(…) constantly.

JavaScript Array Methods Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Double every number, then keep only those over 5.

const result = [1, 2, 3, 4]
  .(n => n * 2)
  .(n => n > 5);
console.log(result); // [6, 8]
Predict the outputmedium

What does this print?

const r = [3, 5, 7].reduce((sum, n) => sum + n, 10);
console.log(r);
Multiple choicemedium

Which method returns the first matching item (not an array)?

Predict the outputmedium

What does this print?

const ages = [12, 19, 25];
console.log(ages.some(a => a < 13), ages.every(a => a > 18));
Fix the bugmedium

The code should log the names of users over 18 in alphabetical order: ["Ana", "Zoe"]. Fix it.

const users = [
  { name: "Zoe", age: 22 },
  { name: "Max", age: 16 },
  { name: "Ana", age: 30 },
];

const adults = users.forEach(u => u.age > 18);
const names = adults.map(u => { u.name });
console.log(names.sort());
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs ["Ana", "Zoe"]
  • No errors

JavaScript Array Methods Quiz

4 questions to check what you learned.

  1. Does map change the original array?

    • Yes
    • No, it returns a new array
    • Only for numbers
    • Only if you use const
  2. What does [1, 2, 3].filter(n => n > 5) return?

    • []
    • undefined
    • null
    • false
  3. What's the difference between sort() and toSorted()?

    • toSorted is alphabetical only
    • There's no difference
    • sort is newer
    • sort changes the original array; toSorted returns a sorted copy
  4. In reduce((acc, n) => acc + n, 0), what is acc?

    • The current index
    • The original array
    • The running result (accumulator) from the previous step
    • Always 0

JavaScript Array Methods Challenge

Order summary

Using array methods (no loops):

  1. itemNames: an array of names, using map
  2. veggie: only items where vegetarian is true, using filter
  3. bill: the total of price * qty for all items, using reduce
  4. Log Bill: 31.5
const order = [
  { name: "Margherita", price: 9, qty: 2, vegetarian: true },
  { name: "Pepperoni", price: 10.5, qty: 1, vegetarian: false },
  { name: "Garlic bread", price: 3, qty: 1, vegetarian: true },
];
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • itemNames is correct
  • veggie has the 2 vegetarian items
  • bill is 31.5
  • Logs "Bill: 31.5"
  • Uses map, filter and reduce