Common JavaScript Array Methods
7 April 2022
For sake of this explanation, we'll set one simple array to work with, a list of people and their ages:
const items = [
{title: 'John', age: 45},
{title: 'Peter', age: 22},
{title: 'Ana', age: 25},
{title: 'Gordon', age: 84},
{title: 'Mike', age: 33},
{title: 'Liz', age: 7}
]
.filter
Returns all items that satisfy condition inside filter method, e.g. people older then 30 years:
const res = items.filter((item) => {
return item.age > 30
})
.find
will find single object in array, the first one it encounters:
const res = items.find((item) => {
return item.title === 'John'
})
.map
Returns new modified array, in this example array of ages only;
const onlyAges = items.map((item) => {
return item.age
})
or this one will create modified version of our example array:
const res = items.map((item) => {
const container = {};
container[item.title] = item.age;
container.months = item.age * 12;
return container
})
.forEach
will iterate through collection of out items:
items.forEach((item) => {
console.log(item.title)
})
.some
will return true
or false
, based on condition inside:
const hasOlderThen50 = items.some((item) => {
return item.age > 50
})
returns true
.includes
will check if array has an value (best for simple checks on simple types):
const items = [1, 2, 3, 4, 5]
items.includes(1) // true
items.includes(10) // false
.every
will return true
only of all items in array are valid against condition inside every
method:
const res = items.every((item) => {
return item.age > 50
})
returns false
, but this one:
const res = items.every((item) => {
return item.age > 0
})
returns true
.
.slice
It will copy and clone array to a new array without changing the original array
const copiedItems = items.slice();
items === copiedItems // will return false
.reduce
Despite missleading name this method execue inside math operation(s) and update/returns variable passed as parameter. In this example 0
is initial value.
const res = items.reduce((currentTotal, item) => {
return item.age + currentTotal
}, 0);
returns 216.
or
const numbers = [7.2, 21.3, 10.5];
const res = numbers.reduce((currentTotal, item) => {
return currentTotal + Math.round(item)
}, 0)
returns 39.