JavaScript Functions and Methods: A Topic-by-Topic Reference · Lesson 6 of 12

Lesson 6: Array Methods, Part 2: map, filter, reduce, sort and more

forEach, map, filter, reduce, some, every, flat, flatMap, sort (and its trap), reverse, and grouping, counting and chaining recipes.

Lesson 6: Array Methods, Part 2: map, filter, reduce, sort and more

These methods take a callback function and are the heart of everyday JavaScript. Most return a new array, so they can be chained.

Visiting every item

forEach(fn)

Runs a function for each item. It returns nothing, so use it for side effects (printing, saving), not to build a value.

["a", "b"].forEach((item, index) => console.log(index, item));

Output:

0 a
1 b

map(fn)

A new array where each item is replaced by what the function returns.

console.log([1, 2, 3].map((n) => n * 10));
console.log(["a", "b"].map((s, i) => `${i}:${s}`));
console.log([{ n: "Ram" }, { n: "Sita" }].map((p) => p.n));
console.log(["1", "2", "3"].map(Number));

Output:

[ 10, 20, 30 ]
[ '0:a', '1:b' ]
[ 'Ram', 'Sita' ]
[ 1, 2, 3 ]

filter(fn)

A new array with only the items for which the function returns true.

console.log([1, 2, 3, 4, 5, 6].filter((n) => n % 2 === 0));
console.log(["a", "", "b", null].filter(Boolean));

Output:

[ 2, 4, 6 ]
[ 'a', 'b' ]

reduce(fn, start)

Combines the items into a single value. The callback gets the running result and the next item.

console.log([1, 2, 3, 4].reduce((sum, n) => sum + n, 0));
console.log([3, 9, 2].reduce((max, n) => (n > max ? n : max)));
const counts = ["a", "b", "a"].reduce((acc, ch) => {
  acc[ch] = (acc[ch] || 0) + 1;
  return acc;
}, {});
console.log(counts);

Output:

10
9
{ a: 2, b: 1 }

some(fn) and every(fn)

some: is at least one item a match? every: are all of them?

const marks = [45, 67, 82];
console.log(marks.every((m) => m >= 40));
console.log(marks.some((m) => m >= 80));
console.log([].every(() => false), [].some(() => true));

Output:

true
true
true false

Flattening

flat(depth) and flatMap(fn)

flat removes one level of nesting (or more with a number, or Infinity). flatMap is map followed by flat.

console.log([1, [2, 3], [4, [5]]].flat());
console.log([1, [2, [3, [4]]]].flat(Infinity));
console.log(["a b", "c"].flatMap((s) => s.split(" ")));

Output:

[ 1, 2, 3, 4, [ 5 ] ]
[ 1, 2, 3, 4 ]
[ 'a', 'b', 'c' ]

Ordering

sort(compareFn)

Sorts in place. Without a function it sorts as text, which surprises people with numbers!

console.log([10, 9, 1, 100].sort());
console.log([10, 9, 1, 100].sort((a, b) => a - b));
console.log([10, 9, 1, 100].sort((a, b) => b - a));

Output:

[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
[ 100, 10, 9, 1 ]

Sorting objects and text

Return a negative number to put a first, positive to put b first. Use localeCompare for text.

const people = [{ n: "Sita", age: 21 }, { n: "Ram", age: 17 }, { n: "Hari", age: 21 }];
console.log(people.sort((a, b) => b.age - a.age || a.n.localeCompare(b.n)).map((p) => p.n));

Output:

[ 'Hari', 'Sita', 'Ram' ]

reverse(), toSorted(), toReversed()

reverse flips in place. toSorted and toReversed (newer: Node 20+, modern browsers) return a new array and leave the original alone.

const a = [3, 1, 2];
console.log(a.toSorted(), a.toReversed());
console.log(a);
console.log([...a].sort());

Output:

[ 1, 2, 3 ] [ 2, 1, 3 ]
[ 3, 1, 2 ]
[ 1, 2, 3 ]

join(glue)

Join items into text.

console.log([1, 2, 3].join("-"));
console.log(["a", null, "b"].join(","));

Output:

1-2-3
a,,b

Recipes with chaining

Chaining: filter, map, reduce together

Each step takes the result of the previous one.

const orders = [
  { item: "pen", price: 10, qty: 3 },
  { item: "book", price: 250, qty: 1 },
  { item: "bag", price: 900, qty: 2 },
];
const total = orders
  .filter((o) => o.price < 500)
  .map((o) => o.price * o.qty)
  .reduce((a, b) => a + b, 0);
console.log(total);

Output:

280

Group by

Collect items into groups by a key.

const words = ["apple", "avocado", "banana", "blueberry", "cherry"];
const groups = words.reduce((acc, w) => {
  (acc[w[0]] ||= []).push(w);
  return acc;
}, {});
console.log(groups);

Output:

{
  a: [ 'apple', 'avocado' ],
  b: [ 'banana', 'blueberry' ],
  c: [ 'cherry' ]
}

Unique values and counting

A Set removes duplicates; reduce counts.

const nums = [3, 1, 3, 2, 1];
console.log([...new Set(nums)]);
console.log(nums.reduce((m, n) => m.set(n, (m.get(n) || 0) + 1), new Map()));

Output:

[ 3, 1, 2 ]
Map(3) { 3 => 2, 1 => 2, 2 => 1 }

Sum, average, min and max

Four everyday numbers from an array.

const n = [4, 8, 15, 16, 23, 42];
const sum = n.reduce((a, b) => a + b, 0);
console.log(sum, sum / n.length, Math.min(...n), Math.max(...n));

Output:

108 18 4 42

Chunks and ranges

Split into pieces and build a number range.

const chunk = (a, size) => Array.from({ length: Math.ceil(a.length / size) }, (_, i) => a.slice(i * size, i * size + size));
console.log(chunk([1, 2, 3, 4, 5], 2));
console.log(Array.from({ length: 5 }, (_, i) => i + 1));

Output:

[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
[ 1, 2, 3, 4, 5 ]

Do not use forEach with await expecting it to wait; use a for...of loop. And do not use map only for side effects: use forEach.

Try it yourself

  1. Get the names of all students who scored above 80, sorted alphabetically.
  2. Compute the total of an array of prices with reduce.
  3. Count how many times each word appears in a sentence.

Next lesson: objects.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 6: Array Methods, Part 2: map, filter, reduce, sort and more | MeroSir