Array methods in JavaScript
The array is a widely used data structure in JavaScript.
You can perform a number of operations on arrays like iteration, inserting items, removing items, filter items, sorting, transformations of item and so on. To do so the array object provides useful built in methods.
Here some of the implementation of array methods in JavaScript.
1. Iterate
1.1 for...of
The for...of
statement creates a loop iterating over iterable objects
for(const item of items)
cycle iterates over array items.
Let’s iterate over a list of colors
:
On each iteration, the variable color
is assigned with the iterated item.
const colors = ['blue', 'green', 'white', 'red'];
for (const color of colors) {
console.log(color);
}
// expected output: "blue"
// expected output: "green"
// expected output: "white"
// expected output: "red"
- You can stop iterating at any time using a
break
statement.
You can use let
instead of const
too, if you reassign the variable inside the block.
const iterable = [10, 20, 30];
for (let value of iterable) {
console.log(value);
}
// 10
// 20
// 30
1.2 for
for(let i; i < array.length; i++)
cycle iterates over array items using an incrementing index variable.
Syntax
for ([initialization]; [condition]; [final-expression])
statement
const colors = ['blue', 'green', 'white'];
for (let index = 0; index < colors.length; index++) {
const color = colors[index];
console.log(color);
}
// 'blue'
// 'green'
// 'white'
index
variable increments from 0
until colors.length - 1
. This variable is used to access the item by index: colors[index]
.
You can stop iterating at any time using a break
statement.
for (let i = 0; i < 5; i++) {
console.log(i);
if(i===3) break;
}
// 1
// 2
// 3
1.3 array.forEach() method
array.forEach(callback)
method iterates over array items by invoking callback
function on every array item.
The forEach()
method executes a provided callback
function once for each array element.
Syntax
// Arrow function
forEach((element) => { ... } )
forEach((element, index) => { ... } )
forEach((element, index, array) => { ... } )
// Callback function
forEach(callbackFn)
// Inline callback function
forEach(function callbackFn(element) { ... })
forEach(function callbackFn(element, index) { ... })
forEach(function callbackFn(element, index, array){ ... })
Parameters
callbackFn
Function to execute on each element. It accepts between one and three arguments:
element
The current element being processed in the array.
index
Optional
The index of element
in the array.
array
Optional
The array forEach()
was called upon.
Let’s iterate over colors
array:
const colors = ['blue', 'green', 'white'];
colors.forEach(function callback(value, index) {
console.log(value, index);
});
// 'blue', 0
// 'green', 1
// 'white', 2
// Arrow function
colors.forEach((color, index)=>console.log(color, index))
array.forEach(callback)
invokes callback
3 times for every item in the array: 'blue'
, 'green'
and 'white'
. and logs the item.
- You cannot break
array.forEach()
iterating.
2. Map
2.1 array.map() method
The map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
array.map(callback)
method creates to a new array by using callback
invocation result on each array item.On each iteration callback(item, index, array)
is invoked with arguments: current item, index and the array itself. It should return the new item.
const numbers = [0, 2, 4];
const newNumbers = numbers.map(function increment(number) {
return number + 1;
});
newNumbers; // => [1, 3, 5]
//Using Arrow function
const array = [1, 4, 9, 16];
// pass a function to map
const map = array.map(x => x * 2);
console.log(ma);
// expected output: Array [2, 8, 18, 32]
numbers.map(increment)
creates a new array from numbers
by incrementing each array item.
array.map()
creates a new mapped array, without mutating the original one.
array.map()
method is used for transformation of data. In REACT we can use this to dynamically render HTML elements from a given array.
2.2 Array.from() function
The Array.from()
static method creates a new, shallow-copied Array instance from an array-like or iterable object.
Array.from(arrayLike, callback)
method creates to a new array by using callback
invocation result on each array item.
On each iteration callback(itm[, index, array])
is invoked with arguments: current item, index and the array itself. It should return the new item.
Let’s increment the numbers of an array:
const numbers = [0, 2, 4];
const newNumbers = Array.from(numbers,
function increment(number) {
return number + 1;
}
);
// newNumbers => [1, 3, 5]
// Array.from(numbers, increment) creates a new array from numbers by incrementing each array item.
// Arrow function
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]
//We can also create an array from a given string
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
Array.from()
creates a new mapped array, without mutating the original one
3. Reduce
3.1 array.reduce() method
The reduce()
method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
On each iteration callback(accumulator, item, index, array])
is invoked with arguments: accumulator, current item, index and the array itself. It should return the accumulator.
Here reduce()
is to return the sum of all the elements in an array
const array = [1, 2, 3, 4];
function reducer(previousValue, currentValue) {
return previousValue + currentValue
}
//Using Arrow funtion
const reducer = (previousValue, currentValue) => previousValue + currentValue;
// 1 + 2 + 3 + 4
console.log(array.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array.reduce(reducer, 5));
// expected output: 15
At first step accumulator
is initialized with 0
. Then reducer
function is invoked on each array item accumulating the sum of numbers.
In the second example accumulator
is initialized with 5.
Then reducer
function is invoked on each array item accumulating the sum of numbers.
- The first array item becomes the initial value if you skip the
initialValue
argument.
4. Concat
4.1 array.concat() method
The concat()
method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
Let’s concatenate 2 arrays of names:
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array = array1.concat(array2);
console.log(array);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
Concatenating three arrays
The following code concatenates three arrays:
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
const numbers = num1.concat(num2, num3);
console.log(numbers);
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
4.2 Spread operator
You can use the spread operator with an array literal to concatenate arrays: [...array1, ...array2]
.
Let’s concatenate 2 arrays of names:
let parts = ['shoulders', 'knees'];
let lyrics = ['head', ...parts, 'and', 'toes'];
// ["head", "shoulders", "knees", "and", "toes"]
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
// arr1 is now [0, 1, 2, 3, 4, 5]
[...arr1, ...arr2, ...arrN]
: you can concat as many arrays as you need using spread operator.
5. Slice
5.1 array.slice() method
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index
of items in that array. The original array will not be modified.
Let’s get some array slices:
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
animals.slice(2)
returns a slice of 2 items. The end
argument defaults to animals.length
.
array.slice()
creates a new array, without mutating the original one.
6. Search
6.1 array.includes() method
The includes() method determines whether an array includes a certain value among its entries, returning true
or false
as appropriate.
array.includes(item, fromIndex)
returns a boolean
whether array
contains item
. The optional argument fromIndex
, defaulting to 0
, indicates the index to start searching.
Let’s determine if 2
and 99
exist in an array of numbers:
const numbers = [1, 2, 3, 4, 5];
numbers.includes(2); // => true
numbers.includes(99); // => false
numbers.includes(2)
returns true
because 2
exists in numbers
array.
numbers.includes(99)
is, however, false
because numbers
doesn’t contain 99
.
- When comparing strings and characters,
includes()
is case-sensitive.
6.2 array.find() method
The find()
method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined
is returned.
On each iteration predicate(item, index, array)
function is invoked with the arguments: iterated item, index and the array itself.
For example, let’s find the first even number:
const numbers = [1, 2, 3, 4, 5];
function isEven(number) {
return number % 2 === 0;
}
const evenNumber = numbers.find(isEven);
evenNumber; // => 2
// Using Arrow function
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
6.3 array.indexOf() method
array.indexOf(item,fromIndex)
returns the index of the first appearance item
in array
. The optional argument fromIndex
, defaulting to 0
, is the index to start searching.
Let’s find the index of 'Joker'
:
const names = ['Batman', 'Catwoman', 'Joker', 'Bane'];
const index = names.indexOf('Joker');
index; // => 2
7. Filter
7.1 array.filter()
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
On each iteration predicate(item, index, array)
function is invoked with the arguments: iterated item, index and the array itself.
Let’s filter an array to have only even numbers:
const numbers = [1, 5, 7, 10];
function isEven(number) {
return number % 2 === 0;
}
const evens = numbers.filter(isEven);
evens; // => [10]
//Arrow function
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
8. Insert
8.1 array.push() method
The push()
method adds one or more elements to the end of an array and returns the new length of the array.
array.push(item1,item2,..., itemN)
method appends one or more items to the end of an array, returning the new length.
let sports = ['soccer', 'baseball']
let total = sports.push('football', 'swimming')
console.log(sports) // ['soccer', 'baseball', 'football', 'swimming']
console.log(total) // 4
array.push()
mutates the array in place
array.push(item1, item2, ..., itemN)
can push multiple items.
9. Remove
9.1 array.pop() method
array.pop()
method removes the last item from an array, then returns that item.
const colors = ['blue', 'green', 'black'];
const lastColor = colors.pop();
lastColor; // => 'black'
colors; // => ['blue', 'green']
colors.pop()
removes the last element of colors
and returns it.
array.pop()
mutates the array in place.
9.2 array.shift() method
array.shift()
method removes the first item from an array, then returns that item.
For example, let’s remove the first element of colors
array:
const colors = ['blue', 'green', 'black'];
const firstColor = colors.shift();
firstColor; // => 'blue'
colors; // => ['green', 'black']
colors.shift()
removes the first element 'blue'
of colors
and returns it.
10. Sort
10.1 array.sort() method
The sort()
method sorts the elements of an array and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
The optional argument compare(a, b)
is a callback that customizes the order of items.
If a
and b
are two elements being compared, then:
- If
compare(a, b)
returns a value > than 0, sortb
beforea
.
- If
compare(a, b)
returns a value < than 0, sorta
beforeb
.
- If
comparFunction(a, b)
returns 0,a
andb
are considered equal.
Let’s sort an array of letters:
const letters = ['B', 'C', 'A'];
letters.sort();
letters; // => ['A', 'B', 'C']
letters.sort()
sorts the letters in ascending order.
We can sort an array of numbers like this.
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
//Arrow function
numbers.sort((a,b)=>a-b);
console.log(numbers);
// [1, 2, 3, 4, 5]
These are some of array methods which are more frequently used. If you want to learn more about JavaScript array method then MDN is a very good resource.