Javascript array methods
An up-to-date list of methods to manipulate arrays in javascript
Introduction
In JavaScript, you can group related elements in a single variable by using arrays. Arrays are a special object data type that allows you to store a list of items in a variable.
An array example is shown below:
const languages = ["English", "Spanish", "Italian"];
An array is often declared using the const keyword.
The values in an array are stored in a list, enclosed by [ ], with each value separated by a comma. The first value in the list is at index 0, so to get a value from the array, we refer to its index.
An example is shown below:
const languages = ["English", "Spanish", "Italian"];
let Britain = languages[0];
console.log(Britain);
//OUTPUT: English
let Spain = languages[1];
console.log(Spain);
//OUTPUT: Spanish
let Italy = languages[2];
console.log(Italy);
//OUTPUT: Italian
Array methods
Learning about array methods can be daunting for beginners. You may wonder if there is an array method for a specific task, when to use a particular method, how the method manipulates the array and how to use the method.
This article covers the use cases of array methods and how they affect the array being worked on. This will make it easier to choose the best method for your particular use case. So, read on as we dive into the world of array methods.
Array methods are built-in functions used to manipulate array values. They act as defined formulas that ease our work with arrays.
The methods can be broadly categorized into:
Methods that mutate original arrays.
Methods that create new arrays.
Methods that return no arrays.
Methods that create arrays.
Methods that mutate original arrays
Mutating means to change in form. Mutating array methods are the methods that change the original array to a newly modified array.
This means that the array is not a copy, but the same array that was passed to the method.
A list of mutating array methods includes:
.unshift( )
This method adds one or more values at the start of an array. It returns a new array with the added values at the array start.
const languages = ["English", "Spanish", "Italian"];
languages.unshift("Russian", "Portuguese");
console.log(languages);
//OUTPUT: ['Russian', 'Portuguese', 'English', 'Spanish', 'Italian']
.push( )
This method adds one or more values at the end of an array. It returns a new array with the added values at the array end.
const languages = ["English", "Spanish", "Italian"];
languages.push("Russian", "Portuguese");
console.log(languages);
//OUTPUT: ['English', 'Spanish', 'Italian', 'Russian', 'Portuguese']
.shift( )
This method removes the first value of an array. It returns a new array without the removed value at the array start.
const languages = ["English", "Spanish", "Italian"];
languages.shift();
console.log(languages);
//OUTPUT:['Spanish', 'Italian']
.pop( )
This method removes the last value of an array. It returns a new array without the removed value at the array end.
const languages = ["English", "Spanish", "Italian"];
languages.pop();
console.log(languages);
//OUTPUT:['English','Spanish']
.splice( )
This method removes any value at the specified index of an array together with the succeeding (after) values of the specified index value. An example is shown below:
const languages = ["English", "Spanish", "Italian"];
languages.splice(1);
console.log(languages);
//OUTPUT:['English']
To remove selected values from an array, you specify the index of the first value to remove, followed by the number of values to remove. An example is shown below:
const languages = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
languages.splice(2,2);
console.log(languages);
//OUTPUT:['English','Spanish', 'Portuguese']
The code above executes by picking the index 2 element which is 'Italian'. It then checks the defined number of elements to be removed which is the next defined value separated by a comma. In this case, we wrote 2 elements to be removed. One is from the defined index and the second is the next index value i.e. 'Italian', 'Russian'.
const languages = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
let removed = languages.splice(2,2);
console.log(removed);
//OUTPUT:['Italian', 'Russian']
We can also store the removed values in a variable and display them as shown above.
.sort( )
This method rearranges array values in ascending order.
An example is shown below:
const languages = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
languages.sort();
console.log(languages);
//OUTPUT:['English', 'Italian', 'Portuguese', 'Russian', 'Spanish']
The sort()
method in JavaScript converts the array values to strings before sorting them. This can lead to errors when sorting numerical data types, because the strings are compared lexicographically (the way numbers are arranged). For example, the number 22
would be considered greater than the number 120
, because the first character of 22
(the letter 2
) comes before the first character of 120
(the letter 1
).
To fix this, you can pass a function to the sort()
method that defines how the array values should be compared. This function should take two array values as input and return a negative number if the first value is less than the second value, a positive number if the first value is greater than the second value, and 0 if the two values are equal.
An example of the function is:
const numbers=[120, 22, 76, 39, 213];
//ASCENDING ORDER
function compareNumbers(a,b){
return a - b;
}
numbers.sort(compareNumbers);
console.log(numbers);
//OUTPUT: [22, 39, 76, 120, 213]
We can also rearrange in descending order by creating the function below;
const numbers=[120, 22, 76, 39, 213];
//DESCENDING ORDER
function compareNumbers(a,b){
return b - a;
}
numbers.sort(compareNumbers);
console.log(numbers);
//OUTPUT: [213, 120, 76, 39, 22]
.reverse( )
This method rearranges array values by flipping, making the last value first and the first value last.
An example is shown below:
const languages = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
languages.reverse();
console.log(languages);
//OUTPUT:['Portuguese', 'Russian', 'Italian', 'Spanish', 'English']
.fill( )
This method changes all the specified array values with the new set value.
By default, if you pass in a value with no other arguments, the fill()
method will replace all existing values in the array with the passed-in value.
An example is shown below to replace all the values with the value passed in the fill method;
const languages = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
languages.fill("Chinese");
console.log(languages);
//OUTPUT: ['Chinese', 'Chinese', 'Chinese', 'Chinese', 'Chinese']
To replace only certain values in an array, we specify the value to replace with, the starting index of the values to replace, and the index up to which to replace. The index up to which to replace is not included in the change, so if you specify the end index 3, with the start index 1, the values at indexes 1 and 2 will be replaced, but the value at index 3 will not be changed.
An example is shown below:
const languages = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
languages.fill("Chinese", 1, 3);
console.log(languages);
//OUTPUT:['English', 'Chinese', 'Chinese', 'Russian', 'Portuguese']
.copyWithin( )
This method is used to move array values into different index positions within the array.
It does not alter the length of the array.
This method can take 3 arguments in the following order in the array:
The index to start copying to. This is the position from which the change starts.
The index to copy. This selected index value becomes the first copy.
The index to stop copying. It does not, however, include this specified index value.
An example is shown below:
const languages = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
languages.copyWithin(0,1,3);
console.log(languages);
//OUTPUT: ['Spanish', 'Italian', 'Italian', 'Russian', 'Portuguese']
Methods that create new arrays.
The methods below are used to create a new array, different from the original while keeping the original.
This means that the original array is not changed.
A list of new array methods includes:
.map( )
This method is used to loop(iterate) over an array giving a new array.
The new array will contain the results of calling a function on each element of the original array. The function that is called by the map()
method is called the callback function. The callback function can be used to manipulate the array values in any way that you want.
An example is shown below to multiple array numbers by two:
const numbers= [2, 3, 4, 5, 6];
//FUNCTION THAT MULTIPLES THE NUMBER BY 2
function doubleNumbers(num){
return num * 2};
const doubledNums= numbers.map(doubleNumbers);
console.log(doubledNums);
//OUTPUT: [4, 6, 8, 10, 12]
.concat( )
This method enables the merging of two or more arrays into one array returned as a new array.
An example is shown below:
const languages1 = ["English", "Spanish", "Italian"];
const languages2 = ["Russian", "Portuguese"];
const allLanguages= languages1.concat(languages2);
console.log(allLanguages);
//OUTPUT: ['English', 'Spanish', 'Italian', 'Russian', 'Portuguese']
An example of merging more than 2 arrays is shown below:
const languages1 = ["English", "Spanish", "Italian"];
const languages2 = ["Russian", "Portuguese"];
const languages3 = ["Chinese", "Swahili"];
const allLanguages= languages1.concat(languages2, languages3);
console.log(allLanguages);
//OUTPUT: ['English', 'Spanish', 'Italian', 'Russian', 'Portuguese', 'Chinese', 'Swahili']
.filter( )
The method is used to filter an array based on a condition. The condition is specified as a function and the filter()
method will return a new array containing only the elements of the original array that meet the condition.
An example is shown below:
const numbers= [21, 31, 41, 51, 61, 71];
//FUNCTION THAT CHECKS NUMBERS BIGGER THAN 50
function biggerNumbers(num){
return num > 50};
const largeNums= numbers.filter(biggerNumbers);
console.log(largeNums);
//OUTPUT: [51, 61, 71]
.slice( )
The method returns a new array with the values between the specified start and end indexes. The end index is not included in the new array, so if you specify the end index as 4, the new array will contain the values at indexes 0 to 3, inclusive.
An example is shown below:
const numbers= [21, 31, 41, 51, 61, 71];
const slicedNums= numbers.slice(0, 4);
console.log(slicedNums);
//OUTPUT: [21, 31, 41, 51]
Not defining the end slice index gives back all the values from the set start index to the end of the array.
An example is shown below:
const numbers= [21, 31, 41, 51, 61, 71];
const slicedNums= numbers.slice(1);
console.log(slicedNums);
//OUTPUT: [31, 41, 51, 61, 71]
To slice the elements from the last index position of the array, we use negative (-).
An example is shown below;
const numbers= [21, 31, 41, 51, 61, 71];
//SLICES ITEMS BETWEEN THE FOURTH FROM LAST TO THE LAST ONE BUT OMMITS THE LAST
const slicedNums1= numbers.slice(-4, -1);
console.log(slicedNums1);
//OUTPUT: [41, 51, 61]
//SLICES FROM THE LAST FOURTHVALUE GOING ONWARDS
const slicedNums2= numbers.slice(-4);
console.log(slicedNums2);
//OUTPUT: [41, 51, 61, 71]
.flat( )
The method flattens a nested array. This means that it takes an array that contains other arrays, and it returns a new array that contains all of the elements from the nested arrays unpacked, one at a time.
An example is shown below for a single nested array:
const nums = [[1,2],[3,4],[5,6]];
const newNums = nums.flat();
console.log(newNums);
//OUTPUT: [1, 2, 3, 4, 5, 6]
It can be used up to unpack all nestings to get only a one-dimensional array. For this, we tell it how deep it unpacks the nested array.
An example is shown below:
const nums = [1,[2,[3,[4]]]];
const newNums = nums.flat(3);
console.log(newNums);
//OUTPUT: [1, 2, 3, 4]
To unpack multiple nested arrays into a single array without having to specify the depth of the nesting, you can use the Infinity
parameter in the flat()
method as shown below:
const nums = [1,[2,[3,[4]]]];
const newNums = nums.flat(Infinity);
console.log(newNums);
//OUTPUT: [1, 2, 3, 4]
.flatMap( )
The method is a combination of the map()
and flat()
methods. It works by mapping each element in an array to a new array and then flattening the resulting arrays.
An example is shown below:
const matchedNums = [
[1,2],
[3,4],
[5,6]
];
function newNums(nums){
return nums[0] + nums[1];
};
const results=matchedNums.flatMap(newNums);
console.log(results);
//OUTPUT: [3, 7, 11]
Methods that return no arrays.
These methods may return a different type of value, such as a number, a string, or a boolean.
Such include:
.includes( )
This method checks if an array contains a passed-in value. It returns true if the array contains or false if it does not.
An example is shown below:
const languages = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
const check=languages.includes("Italian");
console.log(check);
//OUTPUT: true
You can also specify the index of the array to begin the check. This means that the check will start at the specified index and go to the right.
This method does not mutate the original array.
An example is shown below:
const languagesOne = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
const checkOne=languagesOne.includes("Italian",3);
console.log(checkOne);
//OUTPUT: false
const languagesTwo = ["English", "Spanish", "Italian", "Russian", "Portuguese"];
const checkTwo=languagesTwo.includes("Italian",1);
console.log(checkTwo);
//OUTPUT: true
.some( )
The method checks whether at least one element in an array contains the passed-in parameter. If it does, the some()
method returns true, otherwise, it returns false.
This method does not mutate the original array.
An example is shown below:
const numbers= [21, 31, 41, 51, 61, 71];
function greater(num){
return num > 50;
};
const greaterNums=numbers.some(greater);
console.log(greaterNums);
//OUTPUT: true
.every( )
Unlike the some()
method, the every()
method checks whether all elements in an array contain the passed-in parameter. If they do, the method returns true, otherwise, it returns false.
This method does not mutate the original array.
An example is shown below:
const numbers= [21, 31, 41, 51, 61, 71];
function greater(num){
return num > 30;
};
const greaterNums=numbers.every(greater);
console.log(greaterNums);
//OUTPUT: false
.join( )
This method creates a new string from an array.
It uses a comma by default to separate the values but you can specify which separator to use.
An example is shown below:
const languages = ["English", "Spanish", "Italian"];
//NOT SPECIFYING STRING DEFAULT
const newString= languages.join();
console.log(newString);
//OUTPUT: English,Spanish,Italian
You can specify a separator, for example, -, to separate. The separator should be put in quotes.
An example is shown below:
const languages = ["English", "Spanish", "Italian"];
//NOT SPECIFYING STRING DEFAULT
const newString= languages.join("-");
console.log(newString);
//OUTPUT: English-Spanish-Italian
.entries( )
The method returns an array of key-value pairs, which are the index of the element in the array and the value element itself.
When called on an array by itself, the entries()
method returns an object with properties.
Hence, one has to access the values by going down deep into the property items.
An example is shown below:
const languages = ["English", "Spanish", "Italian"];
const new= languages.entries();
console.log(new.next().value);
//OUTPUT: [0, 'English']
To return all array elements and not just one as above, you loop through the array.
This method can be used to convert objects into arrays of index-value pairs.
.reduce( )
This method is used to accumulate array values to a single value.
This is done through a function called on the elements of the array, accumulating the results into a single value. The function is called the reducer function.
The reducer function takes two arguments: the current accumulator value and the current element of the array. The accumulator value is initially set to the initial value of the reduce function, or to undefined if no initial value is provided. The reducer function then returns a new accumulator value, which is then used in the next iteration of the loop. The reduce() method returns the final accumulator value, which is the reduced value of the array.
The original array does not change.
An example is shown below:
const numbers= [21, 31, 41, 51, 61, 71];
function reducing(num, sum){
return sum + num;
}
const reduced= numbers.reduce(reducing);
console.log(reduced);
//OUTPUT: 276
.forEach( )
A function may be created to be used with this method.
This method is used in cases whereby we do not need to use a newly created looped-over array.
The forEach()
method does not return anything. It is an alternative to the map()
method, which returns a new array with the results of the callback function applied to each element of the original array.
An example is shown below:
const numbers= [2, 3, 4, 5, 6];
let sum= 0;
function sumNumbers(num){
return sum= sum + num;
};
numbers.forEach(sumNumbers);
at( )
This method returns the value of an array index that is specified.
An example is shown below:
const languages = ["English", "Spanish", "Italian"];
const spanish= languages.at(1);
console.log(spanish);
//OUTPUT: Spanish
.isArray( )
This method checks if the passed data or object is an array.
It returns true if the object or any value that was created using the array literal syntax and false if not.
An example is shown below:
const languages = "English";
const letters= Array.isArray(languages);
console.log(letters);
//OUTPUT: false
keys( )
This method outputs index values in an array. It returns an array iterator object that contains the indexes of the elements in the array. The indexes are the keys of the elements in the array
An example is shown below:
const languages = ["English", "Spanish", "Italian"];
const keys= languages.keys();
for(const key of keys){
console.log(key);
}
//OUTPUT: 0 1 2
.lastIndexOf( )
This method returns the index of the last occurrence of a value in an array.
This means in cases where the value exists more than once, it checks for the last position occurrence of the array value.
If the value is not found, the method returns -1.
An example is shown below:
const languages = ["English", "Spanish", "Italian", "Spanish"];
let index = languages.lastIndexOf("Spanish");
console.log(index);
//OUTPUT: 3
.length
The length
property returns the number of elements in an array. The count starts at 1, not 0.
An example is shown below:
const languages = ["English", "Spanish", "Italian"];
let length = languages.length;
console.log(length);
//OUTPUT: 3
.toString( )
This method converts an array to a string that is comma separated.
The original array is not changed.
An example is shown below:
const languages = ["English", "Spanish", "Italian"];
let string = languages.toString();
console.log(string);
//OUTPUT: English,Spanish,Italian
Methods that create arrays
These are methods that create a new array and return it.
They include:
.from( )
This method creates an array from an object or data that can be iterated over.
The iterable object can be anything that can be iterated over, such as an array or a string.
An example is shown below:
const languages = "English";
const letters= Array.from(languages);
console.log(letters);
//OUTPUT: ['E', 'n', 'g', 'l', 'i', 's', 'h']
Summary
In summary, the following are some of the most commonly used array methods in JavaScript:
Mutating array methods include:
.unshift( ), .push( ), .shift( ), .pop( ), .splice( ), .sort( ), .reverse( ), .fill( ), .copyWithin( )
New array-forming methods include:
.map( ), .concat( ), .filter( ), .slice( ), .flat( ), .flatMap( )
No array returning methods include:
.includes( ), .some( ), .every( ), .join( ), .entries( ), .reduce( ), .forEach( ), .at( ), .isArray( ), .keys( ), lastIndexOf( ), .length, toString( )
Creating array methods include:
.from( )
Conclusion.
Array methods are popular because they save time and code by providing a way to perform common operations on arrays without having to write custom functions.
Different array methods can be combined to manipulate an array in a desired manner. For example, the push()
and sort()
methods could be combined to add an element to the end of an array and then sort the elements of the array.
However, note that some old browsers may not be compatible with the new array methods. Therefore, it is important to be aware of the compatibility of the array methods that you are using.
That is all for this article.
***Hope you found this article useful. Thanks for the read, feel free to leave a like and a comment.***๐๐