Unays Learn ยท JavaScript

Working with arrays in JavaScript: map, filter and reduce

Arrays hold lists of values, and most programs spend much of their time transforming lists. These methods let you do it in a few clear lines instead of long loops.

Array basics

const scores = [72, 95, 58, 88];
scores.push(64);                  // add to the end
console.log(scores.length);       // 5
console.log(scores.includes(95)); // true
console.log(scores.indexOf(58));  // 2

const stops you replacing the array with a different one, but you can still change what is inside it.

map: change every item

map returns a new array where every item has been transformed by your function:

const scores = [72, 95, 58, 88, 64];
const percents = scores.map(s => s + "%");
console.log(percents); // [ '72%', '95%', '58%', '88%', '64%' ]

filter: keep some items

filter keeps only the items for which your function returns true:

const passed = scores.filter(s => s >= 60);
console.log(passed); // [ 72, 95, 88, 64 ]

find is similar but returns only the first match: scores.find(s => s > 90) gives 95.

reduce: combine into one value

reduce walks through the array carrying a running result. The second argument is the starting value:

const total = scores.reduce((sum, s) => sum + s, 0);
const average = total / scores.length;
console.log(total, average); // 377 75.4

Always give reduce a starting value. Without it, an empty array causes a TypeError.

Arrays of objects

Real data usually comes as a list of objects. The same methods work, and you can chain them:

const students = [
  { name: "Arta", score: 95 },
  { name: "Besa", score: 58 },
  { name: "Dren", score: 88 },
];

const honours = students
  .filter(s => s.score >= 85)
  .map(s => s.name);
console.log(honours); // [ 'Arta', 'Dren' ]

Sorting numbers correctly

By default sort compares items as text, so [10, 9, 100].sort() gives [10, 100, 9]. For numbers, pass a compare function:

const ranked = [...students].sort((a, b) => b.score - a.score);
console.log(ranked.map(s => s.name)); // [ 'Arta', 'Dren', 'Besa' ]

sort changes the original array, so the example copies it first with [...students].

Try it yourself

In Unays Code, make an array of five products with a name and price. Print the names of products under 20, the total price of everything, and the list sorted from cheapest to most expensive.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].