JavaScript array methods and how to use them
Arrays are as central to JavaScript as in many other languages, in this article we will go through the most useful array methods along with creative usage examples.
This article is intended for JavaScript beginners up to an intermediate level that wants to learn tricks and solutions to problems when working with JavaScript arrays.
The article covers the following topics.
The basics
Array .length
Array.prototype.length
, the most basic array property, gives you the length of the array as an integer.
Do note however that length
is also a setter so you can use it to remove elements from the array. If you do myArray.length = 0
you will empty the array.
const array = = [1, 2, 3, 4];
console.log(array.length);
// output: 4
array.length = 2;
console.log(array);
// output: [1, 2]
Array .forEach()
Array.prototype.forEach
loops through the array, it has some slight differences from using the for
keyword, one major being that you cannot break the loop when using .forEach
, still it fits well at the end of chained calls on arrays with .filter
and .map
.
const array = [1, 2, 3, 4];
array
.filter((value) => value > 2)
.forEach((value) => console.log('value is', value);
Array .map()
Array.prototype.map
is extremely useful for transforming data by extracting properties from an array with objects.
const people = [
{
name: 'Anna',
birthDate: '2010-02-21'
},
{
name: 'Dave',
birthDate: '2002-10-26'
},
{
name: 'Sofia',
birthDate: '1985-03-11'
}
]
const names = people.map((person) => person.name);
console.log(names);
// output: ["Anna", "Dave", "Sofia"]
It is also super useful when rendering lists with lit-html:
const names = ['Anna', 'Dave', 'Sofia'];
const template = html`
<ul>
${names.map((name, index) => html`<li>${name} (position ${index}</li>`)}
</ul>
`;
Array .filter()
Array.prototype.filter
returns a new filtered array:
const scores = [45, 23, 76, 55, 13, 42];
const above30 = scores.filter((score) => score > 30);
console.log(above30);
// output: [45, 76, 55, 42]
A neat trick is to use the Boolean
constructor as the filter function to filter an array from nullish values:
const names = ['Anna', '', 'Peter', undefined, 'Andrea'].filter(Boolean);
console.log(names);
// output: ['Anna', 'Peter', 'Andrea']
Array .concat()
Array.prototype.concat
returns a new array from two or more separate values:
const names1 = ['Anna', 'Jenny'];
const names2 = ['John', 'Mary'];
console.log(names1.concat(names2);
// output: ['Anna', 'Jenny', 'John', 'Mary']
Array .sort()
Sorts an array (in place), either through the built-in comparator function or via a custom one returning -1, 0, or 1 to indicate the direction to sort the current item in.
// Default sorting
const array = [435, 7, 34, 673, 43, 2, 7, 23];
array.sort();
console.log(array);
// output: [2, 7, 7, 23, 34, 43, 435, 673]
// Sorting and array of objects
const people = [
{name: 'Anders', age: 62},
{name: 'Sara', age: 32},
{name: 'Anna', age: 43},
{name: 'Evan', age: 17}
];
people.sort((personA, personB) => {
if (personA.age < personB.age) {
return -1;
} else if (personA.age > personB.age) {
return 1;
}
return 0;
});
console.log(people);
// output: [
// {name: 'Evan', age: 17},
// {name: 'Sara', age: 32},
// {name: 'Anna', age: 43},
// {name: 'Anders', age: 62}
// ]
The ones you might want to use more
Now we have covered the basics, let's have a look at some of the more advanced array practices. These are powerful tools to have when transforming data with JavaScript.
Array .splice()
One of the most versatile array methods, it can be used for both adding and removing items from an array, it will also return any removed values as a new array.
The arguments are const removedValues = array.splice(startIndex, removeCount, ...valuesToAdd);
which makes this method useful for a variaty of cases.
// Remove the fist value
const array1 = [1, 2, 3, 4];
const first = array1.splice(0, 1);
console.log(first, array1);
// output: [1], [2, 3, 4]
// Remove the last value
const array2 = [1, 2, 3, 4];
const last = array2.splice(-1, 1);
console.log(last, array2);
// output: [4], [1, 2, 3]
// Add value to beginning of array
const array3 = [1, 2, 3, 4];
array3.splice(0, 1, 10);
console.log(array3);
// output: [10, 1, 2, 3, 4]
// Add value to end of array
const array4 = [1, 2, 3, 4];
array4.splice(array4.length, 1, 10);
console.log(array4);
// output: [1, 2, 3, 4, 10]
Array .reduce()
Array.prototype.reduce
, is familiar for many working with flux patterns where it is used to apply a set of actions to update a state.
Reduce lets you loop through an array and apply each array value in the specified order to produce a result.
The simplest example would be to add an array of integers.
const input = [1, 2, 3, 4];
const sum = number.reduce((accumulator, value) => accumulator + value, 0);
console.log(sum);
// output: 10
A more interesting use would be to create pipelines of composing functions that can generate a final result.
function half(value) {
return value / 2;
}
function squareRoot(value) {
return Math.sqrt(value);
}
function add(term) {
return (value) => value + term;
}
function multiply(factor) {
return (value) => value * factor;
}
const input = 10;
const pipeline = [half, squareRoot, add(5), multiply(3.14)];
const result = pipeline.reduce(
(accumulator, method) => method(accumulator),
input
);
console.log(result);
// output: 22.72125344934934
Now imagine that you might use this for image editing to apply various filters in a specific order:
function applyFilters(pipeline, image) {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
const pixels = context.getImageData(0, 0, canvas.width, canvas.height);
const filteredPixels = pipeline.reduce((accumulator, filter) => filter(accumulator), pixels);
context.putImageData(filteredPixels, 0, 0);
image.src = canvas.toDataURL();
}
function brightness(adjustment) {
return (pixels) => {
const data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
data[i] += adjustment;
data[i + 1] += adjustment;
data[i + 2] += adjustment;
}
return pixels;
};
}
function grayscale(pixels) {
const data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
// Compensate for how human eye percieves colors
// https://en.wikipedia.org/wiki/Relative_luminance#Relative_luminance_in_colorimetric_spaces
const value = 0.2126 * r + 0.7152 * g + 0.0722 * b;
data[i] = value;
data[i + 1] = value;
data[i + 2] = value;
}
return pixels;
}
function opacity(adjustment) {
return (pixels) => {
const data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
data[i + 3] = adjustment;
}
return pixels;
};
}
// Usage
const image = document.querySelector('img');
applyFilters([grayscale, brightness(2.3), opacity(0.7)], image);
Now you could keep adding up the filters and create ever more complicated pipelines.
Pretty cool!
Array .includes()
Array.prototype.includes
returns a Boolean
indicating whether the array includes the given value.
console.log([3, 4].includes(4));
// output: true
This method can also be used to reduce or conditions in if statements:
// Instead of
if (value === 'dropdown' || value === 'buttons' || value === 'radio') {
}
// Use .includes
const allowedValues = ['dropdown', 'buttons', 'radio'];
if (allowedValues.includes(value)) {
}
This increases the readability of the code a lot!
Note: Sometimes .includes
can be easily confused with the .contains
method that the .classList
of elements use. Arrays uses .includes
and only .includes
.
Array .entries()
Array.prototype.entries
returns a key/value iterator that can be used in a for-of loop along with array destructuring syntax.
const words = ['alpha', 'beta', 'gamma'];
for (const [index, word] of words.entries()) {
console.log(index, word);
}
// output: 0 alpha
// 1 beta
// 2 gamma
Array .keys()
Array.prototype.keys
returns an iterator for all keys inside an array:
const words = ['alpha', 'beta', 'gamma'];
for (const index of words.keys()) {
console.log(index);
}
// output: 0
// 1
// 2
Array with unique values (using spread operator with Set)
To get only the unique values from an array you can use a combination of the spread syntax and the Set
constructor (Set is a constructor that can only contain unique values, any duplicates will be ignored).
const array = [1, 4, 5, 6, 6, 4, 3, 2, 1];
const unique = [...new Set(array)];
console.log(unique);
// output: [1, 4, 5, 6, 3, 2]
That is all for now! Keep up the practice of learning.