Hey guys 👋
There are a lot of array methods in JavaScript and often we get confused 😕 about which to use when.
In this article I will summarise these methods and do my best to clear about which method should we use according to our needs.
Let's get started 🚀
As I said we will study the array methods according to our needs, so just think what do you want...
I want...
1. to mutate the original array
a) add to original array
i) .push
:
this method adds an element to the end of the original array and returns the new length of the array.
let numbers = [1,2,3];
number.push(4);
console.log(numbers) // [1,2,3,4]
ii) .unshift
:
this method is like .push
method, except it adds the element at the start of the original array.
let numbers = [2,3,4];
numbers.unshift(1);
console.log(numbers) // [1,2,3,4]
b) remove from the original array
i) .pop
:
this method removes the last element of the array and returns the removed element.
let names = ['Sid', 'Marty', 'John'];
const removedName = names.pop();
console.log(names) // ['Sid', 'Marty']
console.log(removedName) // 'John'
ii) .shift
:
.shift
is just like .pop
except it removes the element from the start.
iii) .splice
:
this method is bit tricky, it can remove and/or add the element(s) to the original array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// At position 2, remove 1 element and add 2 elements:
fruits.splice(2, 1, "Lemon", "Kiwi");
console.log(fruits) // ["Banana", "Orange", "Lemon", "Kiwi", "Mongo"]
Other mutating array methods:
i) .reverse
this method reverses an array. The first element becomes the last, and the last array becomes the first.
const array = [1,2,3,4,5]
array.reverse();
console.log(array);
// [5,4,3,2,1]
ii) .sort
this method sorts the array in place and also returns the sorted array. This method converts all the element to string and sorts them in ascending order by default.
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// [1, 100000, 21, 30, 4]
.sort
receives an optional parameter a compare function, which can be used to override the default behaviour of .sort
.
If compare function is supplied all array elements are sorted according to the return value of the compare function.
compare function receives two arguments say a
and b
. Where a
is first element for comparison and b
is second element for comparison.
- If compareFunction(a, b) returns a value > than 0, sort b before a.
- If compareFunction(a, b) returns a value < than 0, sort a before b.
- If compareFunction(a, b) returns 0, a and b are considered equal.
I know it sounds confusing 😅 , take a look at the example 👇.
let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => {
return a - b;
})
console.log(numbers);
// [1,2,3,4,5]
iii) .fill
The .fill
method changes all elements in an array to provided value, from a start index (which is 0 by default) to an end index (which is length of the array by default).
const array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array1.fill(5, 1));
// [1, 5, 5, 5]
console.log(array1.fill(6));
// [6, 6, 6, 6]
2. a new array
If you want a new array, please look at the following array methods:
i) .map
:
As a react developer, .map
is the most used array method for me. It loops over the array and perform a certain action on each element then returns the new array of the same length.
const numbers = [1,2,3,4];
const numberSqr = numbers.map((num) => num*num);
console.log(numberSqr) // [1,4,9,16]
.map
receives a callback function, which accepts the following arguments:
i) The currentelement
being processed in the array.
ii)index
of the currentelement
being processed in the array.
iii)array
on which.map
was called.value returned from the callback function will be mapped the corresponding element in the array.
ii) .filter
:
This methods creates a new array with all the elements that passed the condition given in the callback function.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// ["exuberant", "destruction", "present"]
iii) .slice
:
This method returns a copy of the portion of the array.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// ["camel", "duck"]
iv) .concat
:
This method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];
letters.concat(numbers);
// result is ['a', 'b', 'c', 1, 2, 3]
3. an array index
i) .indexOf
:
This method returns the first index at which a given element can be found in the array, or -1 if it is not present.
const fruits = ['Banana', 'Apple', 'Kiwi'];
console.log(fruits.indexOf('Apple')) // 1
console.log(fruits.indexOf('Orange')) // -1
ii) .findIndex
:
This method returns the index of the first element that passed a given condition. Otherwise -1 indicating that no element passed the condition.
const numbers = [5,9,2,11,5];
const index = numbers.findIndex((element) => element > 8) // 2
const ind = numbers.findIndex((element) => element > 12) // -1
4. an array element
.find
:
This method returns the first element which satisfies a provided condition. undefined
otherwise.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// 12
5. to know if the array includes
i) .includes
:
This methods returns true
(if the array contains the element) or false
.
const friends = ['Jon', 'Joe', 'Jack', 'Jill'];
console.log(friends.includes('Jon')) // true
console.log(friends.includes('Sid')) // false
ii) .some
:
Name of this method sometimes confuse me 😣. This method returns true
if at least one element passes the given condition.
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true
iii) .every
:
This method returns true
if all the elements in the array pass the given condition, false
otherwise.
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
6. a new string
.join
:
This methods joins all the element of the array by a given string separator and return the string.
let words = ['JS', 'is', 'amazing'];
// joining the words by space
console.log(words.join(' ')) // 'JS is amazing'
// joining by dash ('-')
console.log(words.join('-')) // 'JS-is-amazing'
7. to just loop over an array
forEach
:
This method executes a provided function once for each array element.
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// 'a'
// 'b'
// 'c'
8. to transform the array to a single value
.reduce
:
This methods reduces the array to a single value
.
This value
can be of any type: number
, string
, boolean
, array
or object
.
The reducer function takes four arguments:
a) Accumulator
b) Current Value
c) Current Index
d) Source Array
Reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value.
// sum of the elements of the array using .reduce
let numbers = [1,4,5];
const sum = numbers.reduce((acc, el, i, arr) => acc+el);
console.log(sum) // 10
Phew, this was a lot to take in 😅.
I hope you guys found this article helpful, if you did please leave a like.
Find me on twitter.
Top comments (0)