JavaScript Array Functions
Last Updated: 10 June 2022
.forEach
For when you want to execute the callback on every element of an array
forEach(callbackFn, thisArg)
You have
const numArray = [{
x: 1
}, {
x: 2
}, {
x: 3
}];
You want
// To print out all values in the array
1
2
3
You do
numArray.forEach((element) => {
console.log(element.x);
});
.map()
For when you want to execute the callback for each value in the array and returns each new value in the resulting array.
map(callbackFn, thisArg)
You have
var fruits = [{
quantity: 10,
name: 'apple'
},
{
quantity: 20,
name: 'pear'
},
{
quantity: 30,
name: 'orange'
}
];
You want
[10, 20, 30]
You do
var fruitQuantity = fruits.map(function(fruit) {
return fruit.id
});
Or in ES6
const fruitQuantity = fruits.map(fruit => fruit.id);
You have
const numArray = [{
x: 1
}, {
x: 2
}, {
x: 3
}];
You want
[{
x: 2
}, {
x: 4
}, {
x: 6
}];
You do
const newNumArray = numArray.map(element => {
return {
x: element.x * 2
};
});
.reduce()
For when you want to generate a single value or object from an array.
reduce(callbackFn, initialValue)
You have
var fruits = [{
quantity: 10,
name: 'apple'
},
{
quantity: 20,
name: 'pear'
},
{
quantity: 30,
name: 'orange'
}
];
You want
// To know the total quantity of fruits.
// In this case totalQuantity = 60
You do
var totalQuantity = fruits.reduce(function(total, fruit) {
return total + fruit.quantity;
}, 0);
Or in ES6
const totalQuantity = fruits.reduce((total, fruit) => total + fruit.quantity, 0);
You want
// To find which fruit you have the most of
You do
var mostFruit = fruits.reduce(function (most, fruit) {
return (most.quantity || 0) > fruit.quantity ? most : fruit;
}, {});
You have
const people = [{
name: 'John',
group: 'A'
},
{
name: 'Andrew',
group: 'C'
},
{
name: 'Peter',
group: 'A'
},
{
name: 'James',
group: 'B'
},
{
name: 'Hanna',
group: 'A'
},
{
name: 'Adam',
group: 'B'
}
];
You want
// To get the number of people per group
// {A: 3, C: 1, B: 2}
You do
const groupInfo = people.reduce((groups, person) => {
const {
A = 0, B = 0, C = 0
} = groups;
if (person.group === 'A') {
return {
...groups,
A: A + 1
};
} else if (person.group === 'B') {
return {
...groups,
B: B + 1
};
} else {
return {
...groups,
C: C + 1
};
}
}, {});
You have
const people = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]
You want
// To get the count of each number
// {2: 5, 4: 1, 5: 3, 9: 1}
You do
const occurrences = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (
acc,
curr
) {
return acc[curr] ? ++acc[curr] : (acc[curr] = 1), acc
},
{})
.filter()
For when you want to get a list of element that pass certain tests.
filter(callbackFn, thisArg)
You have
var foods = [{
quantity: 10,
name: 'apple'
type: 'fruit'
},
{
quantity: 20,
name: 'pear'
type: 'fruit'
},
{
quantity: 30,
name: 'carrot'
type: 'vegetable'
},
{
quantity: 30,
name: 'cucumber'
type: 'vegetable'
}
];
You want
// To find which food are fruits and which are vegetables
You do
var vegetables = foods.filter(function(food) {
return food.type === "vegetable";
});
var fruits = foods.filter(function(food) {
return food.type === "fruit";
});
Or in ES6
const vegetables = foods.filter(food => food.type === "vegetable");
const fruits = foods.filter(food => food.type === "fruit");
.sort()
You want to sort an array.
sort(compareFn)
You have
const people = [{
name: "Bob",
age: 15
},
{
name: "John",
age: 23
},
{
name: "Sally",
age: 34
},
{
name: "Tom",
age: 41
}
];
You want
// To sort people by age
You do
let sortByAge = people.sort(function(person1, person2) {
return person1.age - person2.age;
});
.find()
You want to find an element in the array that match your test.
find(callbackFn, thisArg)
You have
const people = [{
name: "Bob",
age: 15
},
{
name: "John",
age: 23
},
{
name: "Sally",
age: 34
},
{
name: "Tom",
age: 41
}
];
You want
// To find the person named John
You do
const john = people.find(person => person.name === 'John');
.some()
You want to see if any of the elements in an array pass your test
some(callbackFn, thisArg)
You have
const people = [{
name: "Bob",
age: 15
},
{
name: "John",
age: 23
},
{
name: "Sally",
age: 34
},
{
name: "Tom",
age: 41
}
];
You want
// To see if any anyone is an adult
You do
const anyAdult = people.some(person => person.age >= 18);
.every()
You want to test whether every element of an array satisfies a specified condition.
every(callbackFn, thisArg)
You have
let numbers = [-2, -1, 0, 1, 3, 5];
You want
// To know if all numbers in the array are greater than 0
You do
let result = numbers.every(function (e) { return e > 0; });
Combining .map(), .reduce(), and .filter()
Since all three are called on arrays and since .map()
and .filter()
both return arrays, we can easily chain our calls.
Let’s check out another example. Here’s our data:
var games = [{
name: "Fallout 3",
ignScore: 85,
metacriticScore: 87,
isFPS: true,
},
{
name: "Call of Duty 2",
ignScore: 90,
metacriticScore: 85,
isFPS: true,
},
{
name: "The Witcher 3",
ignScore: 95,
metacriticScore: 97,
isFPS: false,
},
];
You want Our objective: get the total score of FPS games.
You do
var fpsScore = games
.filter(function (game) {
return game.isFPS;
})
.map(function (game) {
return game.ignScore + game.metacriticScore;
})
.reduce(function (total, score) {
return total + score;
}, 0);
And look how pretty it is with arrow functions:
const fpsScore = games
.filter(game => game.isFPS)
.map(game => game.ignScore + game.metacriticScore)
.reduce((total, score) => total + score, 0);