Array Methods in JavaScript

Arrays are special objects in JavaScript that we use to store collections of values. JavaScript offers several built-in methods and properties that allow us to manipulate the arrays. In this tutorial, let us explore all the JavaScript array methods with an example of each.

Array Methods

Following are all the methods available on arrays in JavaScript

Check if it is an Array

IsArray

The IsArray method allows you to check whether a given value is an array. It returns a true if the value is an array and a false if it is not.

IsArray is the preferred method over instanceOf because it works across realms.

isArray method added in the ES5 version of JavaScript. Hence will not work in older browsers.

The code below uses the isArray method to check if the given value is an array.

Create Array

from

The Array from method creates a new array from an iterable object or array-like object.

An “iterable object” is anything we can iterate over item by item. For example, arrays, objects, and strings are iterable in JavaScript.

An array-like object is an object which looks like an array but is not an array. 

An object, if it has 

  1. indexed elements (i.e., the object has sequential access to its properties);
  2. has a length property.

For Example, the arrLike object below looks like an array with integer property names and a length property

We can easily convert array-like objects using the from method.

You can read more from the tutorial array from in Javascript.

of

The of is a static method that creates a new Array instance from the arguments we pass to it, regardless of the number or type of the arguments.

The syntax of of method is as follows

Examples of array of method.

It is very similar to an Array constructor, with one difference. The new Array(5) will create an array with five empty elements, while Array.of(5) will create an array with one element of value 5

Read Values

at

The at method allows us to read an element from the array. It takes an integer (both positive and negative) value and returns the element at that index. The array is read backward from the end if we provide a negative integer.

In the code below, arr.at(1) reads the value at index 1. While arr.at(-1) will read the value at index four i.e, (arr.length-1)

Add/Remove/Modify elements

push

The array push method adds new elements to the end of an array. It takes the element to be added as an argument and returns the array’s new length. This method can push scalar values, objects, or another array to an array.

Syntax of the push method is as follows

Here element0, element1, …, elementN are the elements you want to add to the end of the array. You can provide any number of items separated by a comma.

The following example, appends multiple elements to the array by supplying multiple items separated by a comma to the push method.

array push method in JavaScript

pop

The pop method removes and returns the array’s last element. If the array is empty, it will do nothing but return undefined.

It mutates the array and changes its length.

Syntax of the array.pop method is follows

In the following code. we create an array of numbers and then call the pop() method on it. The method removes the last element from the array, the number 5, and returns its value. We store the returned value in a variable named lastNumber. Finally, we log the modified array and the removed value to the console.

You can read more about from the tutorial array pop method in JavaScript

unshift

The array Unshift method is a built-in JavaScript method that adds new elements to the beginning of an array. It takes the element to be added as an argument and returns the array’s new length. This method can insert scalar values, objects, or another array into an array.

The syntax for the unshift() method is as follows:

Here, the array is the array to which we want to add elements, and element1element2, …, and elementN are the elements we want to add to the beginning of the array. Note that this method can add as many elements as we want.

The code below inserts multiple elements to the numbers array.

shift

The array shift method removes and returns the first element from the array. If the array is empty, it will do nothing but return undefined.

It mutates the array and changes its length.

The syntax of the array.shift method is as follows:

It does not take any arguments.

In the following example, we have an array of numbers. We call the shift method on it. It removes the first element, number 1, from the array and returns its value.

You’ll be able to read more about the tutorial array shift in Javascript.

splice

The splice method removes or replaces existing elements with new elements in an array. We can also insert new elements at any specific location in the array.

Syntax of the splice method as follows

The splice method usually accepts three arguments

  1. The start is the index of the array where we start changing the array.
  2. deleteCount is the number of items to be removed from the start index
  3. item1, item2, itemN, etc., are the elements to add to the array at the index start

The code below inserts the value 4 at index 3. It will remove 0 any elements from the array.

The following code inserts 9,10 & 11 at index location 3. It also removes the three elements starting from location 3.

The code below removes the two items from the array starting from index 2.

CopyWithin

The copyWithin method is a built-in method that allows us to copy a sequence of elements within an array to another location within the same array, overwriting any existing elements.

copyWithin does not change the length of the array. It copies the elements until the end of the array.length. It will discard anything beyond the array.length.

The syntax for the copyWithin method is as follows.

Where the target is the index of the element to copy the sequence to, the start is the index of the first element to copy from, and the end is the index of the last element to copy from (but not including).

If any of the argument is a negative integer, the index counts backward from the array’s end.

In this example, we start with an array [1, 2, 3, 4, 5], and we want to copy the sequence of items from index 0 to 1 (2 elements) to index 3 & 4.

Hence, we invoke the copyWithin(3, 0,2).

Here 2 is the target, and 0 is the index of the first element. The 2 is the value of the end argument, which is the following index after the end of the sequence, so we copy two elements in total.

You can refer to the article copyWithin in Javascript

fill

The array fill method allows you to set the elements of an array to a specific value.

Syntax of the fill method as follows

The value parameter is the value that you want to fill the array with.

The start is the starting index from where you’d like to fill the array. It is optional and defaults to index 0.

The end is the ending index up to which you want to fill. It is optional and defaults to the array’s last index (array.length – 1) if omitted.

The start and end can have negative values. In that case, it will count back from the array’s end.

The code below creates a new array from the array constructor function. It will then fills it up with 0 value

The code below fills up the portion of the array using fill method.

Sorting Arrays

sort

The sort method accepts a callback function as an argument and sorts the array using that function. The callback function (known as compareFn) is optional. The sort method will use the default sort if we omit the callback function. The default sorting method converts each element into strings (casts them to strings) and compares their values according to the UTF-16 encoding standard.

The syntax of the sort() method is as follows:

The following code sorts the array of numbers. As you can see from the output, 7000 has come before 2000, 21 & 5 because the default sort method converts numbers to strings and then sorts them in ascending order.

To customize the sorting order, we need to provide the compare function. The syntax of which is as follows.

The compareFn accepts two parameters, a and b, corresponding to the two elements of the array that we are comparing. A positive return value will sort a after b, a negative value will sort b after a, and 0 will keep the original order.

The code below sorts the numbers array in ascending order using the sortNumbers callback function.

instead of separate function, you can make use of arrow function.

You can learn more about how to sort arrays in JavaScript.

reverse

The reverse method reverses the order of the elements in an array. It moves first element to last, the second to second last, and so on.

The syntax for the reverse method is as follows:

The reverse method mutates the original array, meaning it modifies the array in place and returns a reference to the same array with the reversed order of elements.

The following example shows how to use the reverse method on an array.

Merge & Split Arrays

concat

The concat method combines two or more arrays into a new single array and then returns that array. It does not change the original array but returns a new array.

The syntax for the concat() method is as follows:

array is the original array that you want to join with other arrays or values.

The value is the value we want to merge with the original array. It can be an array or just any value. The concat will create a shallow copy of the original array if we omit the values.

The concat will not change the original array. It will always return the new array.

In this example, we create two arrays, numArr1, and numArr2 and then use the concat method to combine them into a new array called numbers.

The code below merges two arrays and a few numbers into a new array.

Slice

The slice method extracts a portion of an existing array and returns it as a new array.

The syntax of the slice method is as follows.

Where start is the starting index, and the end is the ending index of the array section we want to extract.

Slice creates a new array that contains all the elements from the start index up to the end -1 index. Note that it will not copy the element at the end index.

If we omit the start, it will default to 0. If we omit the end, it will default to array.length.

The code below copies the elements from the index 0 to 3 to a new array.

The code below copies everything from the original array to the new array. The numArr.slice() is equivalent to numArr.slice(0,numArr.length);

Flatten Array

Join

The join method joins the elements of an array into a string.

If the array has only one item, it will return it.

If the array has more than one item, it will concatenate each element separated by a separator and returns it.

We can specify the separator as the first argument.

It will treat undefined, null, and empty slots as empty strings.

Syntax

Where the separator is the separator that you wish to use, if omitted, it will use the comma.

The following example creates an array of fruits. It shows how you can use the join statement to convert them into a string.

flat

The flat method lets us flatten a nested array into an array of single dimensions.

The syntax for using the flat is as follows.

Where array is the array we want to flatten.

The depth is an optional argument that specifies the maximum nesting depth to flatten.

For example, if we set the depth as 2, the flat will flatten nested arrays until depth 2. nested arrays beyond depth 2 will return unchanged.

If we omit the depth, it will default to 1.

If the depth is 0, the flat method will return the original array unchanged.

In the code below, the nestedArray is an array with depth 2.

flatMap

The flatMap method transforms the original array using a map function and then flattens it to the depth of 1.

The flatMap iterates over an array, execute a provided map function once for every array element, and uses the result to create a new array. It then flattens the array to a depth of 1.

It is similar to the calling map method followed by the flat method with a depth of 1. But it is slightly more efficient than calling those two methods separately.

The syntax of flatMap is as follows:

The flatMap method takes in two optional parameters

callbackFn- A function that flatMap invokes for each element of the array. The callback function returns an array, then flattened and concatenated with the output array. This function takes up to three arguments (element, index, array). The syntax is as follows

The element parameter is the current element being processed, the index parameter is the current element’s index, and the array parameter is the array being processed. 

thisArg – An optional parameter that specifies the value to be used as this when executing the callback function.

The code below contains array of numbers. The callback function multiplies each element by 2 and returns the array, which is then flattened 

Search

indexOf

The indexOf method searches for a given element within a given array. It starts searching for the items from index 0 and returns the index of the first occurrence of the given element in the array. If the element does not exist, then it will return -1.

The syntax of the indexOf method is as follows:

Where element is the element to be searched in the array, and startIndex is the optional index from which to start the search.

If the startIndex is negative, the search will start from the startIndex + array.length. i.e., it will count back from the end of the array

LastIndexOf

The lastIndexOf method searches for a given element within a given array. It starts searching for the item from the last index of the array and searches backward. Hence it returns the index of the last occurrence of the given element. If the element does not exist, then it will return -1.

The syntax of the lastIndex is as follows

The element is the element to be searched in the array, and fromIndex is the optional index from which to start the search. Note that the search will begin from fromIndex and searches backwards until the index 0.

If the fromIndex is negative, the search will start from the fromIndex + array.length. i.e., it will count back from the end of the array

includes

The includes method checks if a certain element exists in the array. If it exists, it returns true else, false.

The syntax of includes method is as follows.

The searchElement is the element to be searched in the array, and fromIndex is the optional index from which to start the search.

find

The find method searches elements in the array using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the first element that matches the criteria. Else returns undefined.

The syntax of the find method is as follows.

Where callbackFn is a function that find method invokes for each element of the array. It will contain the logic to check elements of the array. The callbackFn takes up to three arguments (element, index, array) and must return true if the element matches the search criteria.

In the code below, we have an array of fruits. We are using the find() method to search for the element ‘mango’. The findLogic is the callback function, which returns true if the value of the element is mango and else false.

You can also use an arrow function.

findIndex

The findIndex method searches elements in the array using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the index of the first element that matches the criteria. Else returns -1.

The findIndex is the same as the find method. The only difference is that the find returns the value of the element while findIndex returns its index.

The syntax of the findIndex is as follows.

Example of findIndex

findLast

The findLast method searches elements in the array in reverse order using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the first element that matches the criteria. Else returns undefined.

findLast is similar to the find method. The find method searches from the beginning of the array, and the findLast searches from the end of the array.

The syntax of the findLast method is as follows.

The following is an example of the findLast method.

findLastIndex

The findLastIndex is similar to the findLast method. It searches elements in the array in reverse order using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the index of the element that matches the criteria. Else returns -1

The findLast returns the matching element, while findLastIndex returns the index of the matching element.

The syntax of the findLastIndex method is as follows.

The following is an example of the findLastIndex method.

Loop 

forEach

The forEach method iterates over an array and executes a provided function once for every array element.

forEach method can be used as an alternative to looping statements like for, for…of, and for…in.

The syntax of forEach is as follows.

callbackFn- A function that forEach method invokes for each element of the array. The callbackFn takes up to three arguments (element, index, array). The syntax is as follows.

The element parameter is the current element being processed, the index parameter is the current element’s index, and the array parameter is the array being processed.

In this code, we declare an anonymous callback function that simply logs each element to the console.

entries

The entries method allows us to create an iterator object from an array containing each index’s key/value pairs.

Each key-value pair the entries method returns is an array with two elements. The first element is the index number, and the second is its corresponding value.

The syntax of the entries method is as follows.

The code below uses the for of loop to iterate over iterated returned by the entries method. The element in the array is “a” and its index position is 0. Hence the iterator returns [ 0, ‘a’ ]

Values

The values method allows us to create an iterator object from an array containing the values of each element in an array in the order they appear.

It is similar to entries method, but only returns the values. The keys method returns the only keys.

The syntax of the values method is as follows

Example

keys

The Keys method allows us to create an iterator object from an array containing the keys of each element in an array in the order they appear.

It is similar to entries method, but only returns only the keys. It is also similar to values method, which only returns values.

The syntax of the values method is as follows

Example

Transform an Array

map

The array map method allows us to create a new array by transforming each element of an existing array using a callback function. It iterates over each element of an array, invokes the callback function, and uses the result to create a new array.

The Syntax of the map method is as follows.

The callbackFn is the callback function invoked against each element of the existing array.

thisArg is an optional value that becomes the this of executing the callback function.

The Syntax of the callbackFn is as follows.

Where the currentValue is the current element being processed by the map method. Index (optional) is the current element’s index, and array (optional) is the array being processed.

The code below creates a new array doubledNumbers by multiplying each element of the existing array by two.

Filter

Array filter allows us to create a new array by filtering out the elements of a given array. It does that by using a filter function. The filter method iterates over every array element and executes the filter function. It will create a new array with all elements that pass the filter function.

The Syntax of the Javascript filter method is as follows.

The filterFn is the callback function invoked against each element of the existing array. It must return true or false.

thisArg is an optional value that becomes the this of executing the filterFn function.

The Syntax of the callbackFn is as follows.

The currentValue is the current element of the array being processed by the filter method. Index (optional) is the current element’s index, and array (optional) is the array.

The filter method in the following example takes in a number and returns true if the number is odd. The filter method then returns a new array containing only the odd numbers.

Misc

reduce

The reduce method reduces the array to a single value. It iterates over each element of the array and invokes a callback function. The callback function (the reducer function) returns a single output value.

The syntax of the reduce method is as follows.

The reducer function (reducerFn) takes four arguments. The first two arguments are the accumulator and the current value of the array. It returns the updated value of the accumulator, which it will use as the accumulator for the next iteration.

An initialValue is optional and is the initial value of the accumulator. If no value is specified, it will use the first element of the array as the initial value.

The syntax of the reducer function is as follows.

The code below uses the reduce method to calculate the sum of all the elements of a numbers array.

reduceRight

The reduceRight method reduces the array to a single value. It iterates over each array element in descending-index order and invokes a callback function. The callback function (the reducer function) returns a single output value.

The reduceRight is similar to the reduce method. The only difference is that it iterates array in descending order

every

Every method tests to see if all elements in an array pass a particular test. It invokes the callback function on every element of the array. If callback returns true for every element, then the method will return true else, false

The syntax of every method is as follows:

callbackFn is the callback function that the Every method will invoke against each array element.

ThisArg is an optional parameter specifying the value to be used for this when executing the callback function.

The syntax of the callbackFn is as follows:

Where

Element is the current element being processed in the array.

Index (optional) is the index of the current element being processed.

Array (optional) is the array that every() was called upon.

some

Some method tests to see if at least one element in an array pass a particular test. It invokes the callbackFn function on every element of the array. If callBackFn returns true for any one of the element, then the method will return true else, false.

The syntax of every method is as follows:

The syntax is similar to every method

Array Properties

Length

The array length property of the JavaScript array returns the number of elements the array can hold. The length also includes the number of elements plus empty slots (in the case of sparse arrays), if any, in that array. We can also use the length property to increase or shorten the array’s length

Array length property in JavaScript

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top