JavaScript Array Methods

Modern JavaScript has powerful array methods that take a function (a callback) and run it for each item. They replace many loops.


map: change every item

const prices = [100, 200, 300];
const withTax = prices.map(p => p * 1.18);
console.log(withTax);
Output of the above program is

[ 118, 236, 354 ]

map() returns a new array of the same length.


filter: keep some items

const ages = [12, 18, 25, 9, 40];
const adults = ages.filter(a => a >= 18);
console.log(adults);
Output of the above program is

[ 18, 25, 40 ]


reduce: combine into one value

const nums = [1, 2, 3, 4];
const sum = nums.reduce((total, n) => total + n, 0);
console.log(sum);
Output of the above program is

10

The second argument (0) is the starting value of total.


find, some and every

const users = [
  { id: 1, name: "Robin" },
  { id: 2, name: "Maria" }
];

console.log(users.find(u => u.id === 2));
console.log([1, 2, 3].some(n => n > 2));
console.log([1, 2, 3].every(n => n > 2));
Output of the above program is

{ id: 2, name: "Maria" }
true
false

MethodReturns
find()The first item that matches, or undefined
findIndex()Its index, or -1
some()true if at least one item matches
every()true if all items match

sort and reverse

sort() changes the original array, and sorts as text by default. For numbers give a compare function.

const nums = [10, 9, 1];
console.log([...nums].sort());
console.log([...nums].sort((a, b) => a - b));
console.log([...nums].reverse());
Output of the above program is

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

The text sort puts 10 before 9, because “1” comes before “9”. We copy the array with [...nums], so the original is not changed.


Chain methods

const result = [1, 2, 3, 4, 5, 6]
  .filter(n => n % 2 === 0)
  .map(n => n * 10);
console.log(result);
Output of the above program is

[ 20, 40, 60 ]


Summary

  • map transforms, filter selects, reduce combines.
  • find, some and every search.
  • sort needs a compare function for numbers.
  • Next: JavaScript Objects.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.