Array Methods

Programming Languages · JavaScript Objects · 14 min

Use forEach, map, filter, reduce and find to work with whole arrays in one line.

forEach: do something with each item

Arrays have methods that take a function and run it on every item. The simplest is .forEach().

const names = ["Ana", "Bo"];
names.forEach((name) => console.log(name));

It does the same job as a for...of loop, in one line.

  • Use planets.forEach to print Hello, and each planet.

map: change every item

.map() builds a new array by changing every item with your function. The original array stays the same.

const nums = [1, 2, 3];
const bigger = nums.map((n) => n + 10);
console.log(bigger); // [11,12,13]
  • Create doubled by mapping prices to each price times 2.

  • Print doubled.

filter: keep only some items

.filter() keeps the items where your function returns true and drops the rest.

const nums = [1, 6, 3, 9];
const big = nums.filter((n) => n > 5);
console.log(big); // [6,9]
  • Create adults with only the ages that are 18 or more.

  • Print adults, then adults.length.

reduce: boil it down to one value

.reduce() squashes an array into one value, like a total. Your function gets the result so far (sum) and the next item, and returns the new result. The 0 at the end is where sum starts.

const total = [1, 2, 3].reduce((sum, n) => sum + n, 0);
console.log(total); // 6
  • Create total by reducing scores to their sum, starting at 0.

  • Print total.

find: the first match

.find() gives back the first item where your function returns true. If nothing matches, you get undefined, JavaScript's word for "no value".

const nums = [3, 8, 12];
console.log(nums.find((n) => n > 5));   // 8
console.log(nums.find((n) => n > 100)); // undefined
  • Use users.find to print the first name longer than 3 letters.

  • Now print the first name longer than 10 letters (there isn't one).

Put it together: shopping cart

These methods chain nicely, each one feeding the next. Your cart holds item prices. You only want the cheap items, two of each, and then the bill.

  • Create cheap with only the prices under 20.

  • Create twoOfEach by mapping cheap to each price times 2.

  • Add up twoOfEach with reduce and print Total: and the result.

More in JavaScript Objects

Previous: Loops · Next: Objects