Array Method in JavaScript

Video Tutorial
FREE
Array Methods thumbnail
This video belongs to
JavaScript Course With Certification: Unlocking the Power of JavaScript
9 modules
Certificate
Topics Covered

Overview

Arrays in javascript is an object which is used to store multiple values having the same or different data types in a group. That means we can store elements of type Number, Boolean, String, Object, etc.

Arrays are represented by a pair of square brackets []. The values in an array are known as elements, and their position is defined by index (or indices). Each element in an array is separated by commas (,).

What is an Array in JavaScript?

Imagine we are asked to keep track of exam scores of a student, or maybe we are supposed to make a list of grocery items for the month, or maybe we have to track our body temperature throughout the week. All the mentioned tasks have one thing in common, they all are collections of items that we are supposed to store somewhere.

Now being a programmer, an obvious question strikes my mind.

Can we do the above tasks using Javascript? Is there anything that could be used to store a set of items?

The answer is yes! Array.

An array is a javascript object which is defined as a collection of elements of any type or simply a collection of data items stored under a single name. It can be defined as a flexible container that can be used to store items of similar or different data types.

See Also: Array of Objects in JavaScript

Following are some properties of the array in JavaScript:

  • An array can be empty or contain one or more than one elements.
  • The elements of an array can be of similar or different data types.
  • We can store array(s) inside an array in javascript.

How to Create an Array in JavaScript

Now that we have got the basic idea of what an array in Javascript is let's see how to create an array in Javascript.

Following are some ways to create an array in Javascript:

By using Array Literal Method

In this method, we create an array by simply assigning the array values to a variable.

Syntax

  • The arr is the name of the literal which will be assigned the array.
  • The [...] is the array that is being assigned. The items are stored within the square brackets ([ ]) separated by a comma.
  • The array assigned to the literal can be empty or may have multiple items

Example

Explanation of the example

In the above example, we are creating an array groceryList to store strings. The array [ 'egg', 'butter', 'bread' ] is directly assigned to the literal groceryList.

By using Array constructor

Arrays in javascript can be declared using the constructor. In this method, we call the Array() constructor using the new keyword. It returns an array object.

Syntax

  • param is the parameter of the array. It could be the length of the array or items that should be stored in the array.

Example

Explanation of the example

In the above example, arr is an empty array of size 3 and arr2 is an array with elements 'HTML', 'CSS', 'Javascript'.

Getting Elements from an Array in JavaScript

Now that we have learned how to create an array, the question is, "How do we access the items of an array?"

The array in javascript follows 0-based indexing, i.e., The first element of an array is considered as 0-index, the second element of an array is considered as 1-index, and the third element of an array is considered as 2-index and so on.

Following is a pictorial depiction of 0-based indexing:

0-based indexing

How to access the elements of an array?

We can access the elements of an array directly by using its index. To access the element present at a particular index in an array, we need to write down the array variable followed by square brackets within which we need to pass the index.

Syntax

  • arr is the name of the array variable
  • ind is the index value of the element that we are accessing, it ranges between 0 and size of the array with the latter not included.

Example

Output

Explanation of the example

In the above example, the groceryList[0] will access the element present at 0-index, i.e., the first element and will output 'egg'. Similarly, the groceryList[3] will access the element present at 3-index, i.e. the fourth element and will output 'cereals'.

How to Add Elements to an Array in JavaScript?

The arrays in Javascript are dynamic, i.e. we can add or remove elements from an array. In this section, we will learn how to add elements in an array.

There are two ways to add an element to the array:

  • By using the push() method.
  • By using the unshift() method.

Pictorial representation:

Add Elements to an Array in JavaScript

The push() method:

The push() method is used to add an element at the end of an array. The push() method returns the new length of the array.

Syntax

  • The arr is the array in which we are adding the new item.
  • The item is the element that is being added to the array. It can be one or more than one.

Example

Output

Explanation of the example

In the above example, we are given an array groceryList which has three elements. Now, we are adding a new element cereals by groceryList.push(cereals). Thus now, the array will have four elements, that's why the newLength outputs 4 and cereals will be added at the end of the array groceryList.

Note: We can also push more than one item at the same time.

Output

Explanation of the example

In the above example, we are given an array groceryList which has three elements. Now, we are adding two elements 'cereals' and 'Milk' by groceryList.push(cereals, Milk). Thus now, the array will have 5 elements, that's why the newLength outputs 5 and cereals, Milk will be added at the end of the array groceryList.

The unshift() method

The unshift() method is used to add an element at the beginning of the array. The unshift() method returns the new length of the array.

Syntax

  • The arr is the array in which we are adding the new item.
  • The item is the element that is being added to the array. It can be one or more than one.

Example

Output

Explanation of the example

In the above example, we are given an array groceryList which has three elements. Now, we are adding a new element cereals by groceryList.push(cereals). Thus now, the array will have four elements, that's why the newLength outputs 4 and cereals will be added at the beginning of the array groceryList.

Note: We can also unshift more than one item at the same time.

Output

Explanation of the example

In the above example, we are given an array groceryList which has three elements. Now, we are adding two elements 'cereals' and Milk by groceryList.push(cereals, Milk). Thus now, the array will have five elements, that's why the newLength outputs 5 and cereals, Milk will be added at the beginning of the array groceryList.

How to Remove Elements from an Array in JavaScript?

Since arrays are dynamic, there could be situations where we would need to remove elements from the array. Let's learn how to remove elements from the array:

There are two ways to remove an element from the array:

  • By using the pop() method.
  • By using the shift() method.

The pop() method

The pop() method is used to delete the last element of an array. The pop() method returns the deleted element.

Syntax

  • The arr is the array whose last element is to be deleted.
  • It doesn't take any parameters.

Example

Output

Explanation of the example

In the above example, we are given an array groceryList with 5 elements. Now, groceryList.pop() will delete the last item of the groceryList and return the deleted element. Thus deletedItem outputs rice which was the last element of the groceryList and groceryList will output: [ egg, butter, bread, cereals].

The shift() method

The shift() method is used to delete the first element of an array. The shift() method returns the deleted element.

Syntax

  • The arr is the array whose first element is to be deleted.
  • It doesn't take any parameters.

Example

Output

Explanation of the example

In the above example, we are given an array groceryList with five elements. Now, groceryList.shift() will delete the first item of the groceryList and return the deleted element. Thus deletedItem outputs egg which was the first element of the groceryList and groceryList will output: [ butter, bread, cereals, rice].

How to Copy and Clone an Array in JavaScript?

A lot of people have the habit of losing things, and for that reason, it's a good idea to keep a backup. Imagine we are heading out for grocery shopping. Now, we have decided to make a backup of the grocery list, which will be exactly similar to the original list. The naive approach would be to re-write the entire list, but it would be extra work, right? A better approach would be to make a xerox (or copy) of the list.

Now, what if we are creating the above list as an array in Javascript, How do we create a copy or clone of an array in Javascript?

The slice() method in Javascript is used to create the clone of an array in Javascript. It creates a new array which is the shallow copy or the original array. The slice() method doesn't change the original array.

Note: Shallow copy in javascript is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

Syntax

  • The arr is the array whose clone is being created.
  • The slice method returns a new array which is the shallow copy of the original array.

Example

Output

Explanation of the example:

In the above example, we are given an array groceryList. Now we are creating the clone of this array by groceryList.slice(), which returns a new array by shallow copying, which is stored in the groceryListClone. Thus both groceryList and groceryListClone are the same; thus they are outputting the same elements.

Note: We can also create a copy of an array using the spread(...) operator. We'll discuss the spread operator in detail in the later section of this article.

How to Search for a Value in an Array in Javascript

In previous sections, we have learned how to access the element present at a particular index in an array.

But what if we want to do the opposite? Imagine we have an array of numbers and we want to know the index of a particular number. In such cases, the Javascript array search comes into play.

There are four different ways to search for a value in Javascript:

  • By using IndexOf() method
  • By using Find() method
  • By using Includes() method
  • By using Filter() method

indexOf()

This includes() method checks whether a particular element is present in an array or not. It takes the value of the element as an argument and returns the index of the first occurrence of the element. If the element is not present, then it returns -1.

Syntax

  • The arr is the array within which the search operation is performed.
  • The parameter searchElement takes the element that we are searching within the array.
  • The parameter fromIndex sets the position from where the search operation would start. It is an optional parameter. By default, the search starts from the 0th index.

Example

Output

Explanation of the example

In the above example, we are given an array groceryList. The statement groceryList.indexOf('bread') looks up to the array and finds the occurrence of break, thus it outputs 1which is the index of the first occurrence of 'bread'. The statement groceryList.indexOf('peanut') looks up to the array and doesn't find the occurrence of peanut, thus it outputs -1.

find()

The filter() method is used to find the first element that matches the given condition. This method takes a callback function and returns the element that matches the condition. It stops the execution once the required element is found.

Syntax

  • The arr is the array within which the search operation is performed.
  • func is the function that is used to test each element in the given array. It could be an arrow function, a callback function, or an inline callback function.
  • The func takes three parameters:
    • element: The current element being processed in the array.
    • index: The index of the current element being processed in the array. It is an optional parameter.
    • array: The array on which find() was called. It is an optional parameter.

Example

Let's search even elements in an array.

Output

Explanation of the example

In the above example, we are given an array of numbers arr. Now we are supposed to search first even element in the array (i.e., numbers that are divisible by 2), thus we would use the arr.filter(item => item % 2 == 0). The item will take the value of every element present in the array and will compare it with the equation item => item % 2 == 0. If the equation returns true it means that we have found the first even number. Then the find() will stop the execution.

includes()

This includes() method checks whether a particular element is present in an array or not. It takes the value of the element as an argument and returns the boolean result true or false.

Syntax

  • The arr is the array within which the search operation is performed.
  • The parameter searchElement takes the element that we are searching within the array.
  • The parameter fromIndex sets the position from where the search operation would start. It is an optional parameter. By default, the search starts from the 0th index.

filter()

The filter() method is used to find all the elements that match the given condition. This method takes a callback function and returns a new array with all the elements that match the condition.

Syntax

  • The arr is the array within which the search operation is performed.
  • func is the function that is used to test each element in the given array. It could be an arrow function, a callback function or an inline callback function.
  • The func takes three parameters:
    • element: The current element being processed in the array.
    • index: The index of the current element being processed in the array. It is an optional parameter.
    • array: The array on which filter() was called. It is an optional parameter.

Example

Let's search even elements in an array.

Output

Explanation of the example

In the above example, we are given an array of numbers arr. Now we are supposed to search even elements in the array (i.e., numbers that are divisible by 2), thus we would use the arr.filter(item => item % 2 == 0). The item will take the value of every element present in the array and the function will return true when *item % 2 == 0* holds true otherwise, false. Then the filter method will return an array of even numbers, which is stored in evenElements.

Example

Output

Explanation of the example

In the above example, we are given an array groceryList. The statement groceryList.includes('bread') looks up to the array and find the occurrence of break, thus it outputs true. The statement groceryList.includes('peanut') looks up to the array and doesn't find the occurrence of peanut, thus it outputs false.

Array Destructuring in JavaScript

Array destructuring was introduced in the ES6 implementation of JavaScript. It is a simple way of extracting multiple properties from an array by taking its structure and then destructuring it into small parts by assigning the values to separate variables.

But what was the need to introduce Array Destructuring?

Imagine we are given an array, and we want to store its elements in different variables.

The whole process would look something like the following:

Output

Here, we are given an array groceryList with three items, thus in order to store all these items in variables, we have to declare three different variables and assign them the values present at different indexes in the array.

The above method, although it works fine, could be really long and space-taking for larger arrays.

The concept of array destructuring was introduced with ES6 to take the values from the array or properties from the object and set them as local variables in one go. The purpose was to make our code more concise and readable.

Example

Let assign the values of the items of an array using the destructuring syntax:

Output

Explanation of the example

In the above example, we are given an array with three elements, and we are supposed to store them in variables. Now we are directly using the array destructuring syntax and assigning the values to the variables. The assignment will happen sequentially, i.e. itemOne will be assigned 'egg', itemTwo will be assigned 'butter' and so on.

Skipping a Value in an Array

Now in the above section, we have learned how to assign array items to variables. But what if do not want a particular array item to be assigned to any variable?

The array elements can be skipped or ignored while destructuring. To do this, we need to keep the position of the array item in the literal sequence empty.

Example

Output

In the example above, we have skipped the element with index 1 i.e. butter.

Explanation of the example

In the above example, we have kept the second position in the sequence empty which associates with the array element 'butter'. Thus the element 'butter' won't be assigned to any variable, whereas itemOne and itemThree will hold the values 'egg' and 'bread'.

Assigning a Default Value to a Variable

In the previous section we saw how we can skip an array element. But what about the opposite case? Imagine the case when we are passing more no. of variables than the array items. What would happen?

In such cases, the variable will hold the values undefined.

Output

In the above example, the itemThree is not assigned any value, thus it will output undefined.

We can assign the default values to the variables while destructuring an array. This primarily helps in avoiding variables with undefined or no value.

Example

Output

Explanation of the example

In the above example, we have three variables itemOne, itemTwo, itemThree, and we are destructuring an array with two elements. Thus itemOne and itemTwo will hold the values 'egg' and 'butter' respectively. Since the third variable itemThree is not assigned any value, it will hold the default value.

Nested Array Destructuring in JavaScript

A nested array is defined as an array that is stored inside another array. In previous sections, we have learned how we can use an array as an element inside an array.

Now, how do we assign the elements of these nested arrays to variables using the array destructuring?

The following example depicts how we can destructure a nested array.

Example

Output

Explanation of the example

In the above example, we are given an array that has an array nested inside it. Now we want to assign the value 'rice' to a variable. Since we do not want to assign any other values to any variable, other fields will remain empty (if you did not understand this step, please refer to the skipping a Value in an Array section).

Thus, we will skip the first three values in the array. Now, since we are accessing the elements of a nested array, thus the fourth value on the l.h.s will be passed in the form of an array. Now, [,,itemSix] is associating with ['bread', 'cereals', 'rice']. Now, again we will skip the first two items of the array and then pass the variable itemSix, which will hold the value 'rice'.

Using the Spread Syntax and Rest Parameter in JavaScript

The concept of Spread syntax and Rest parameter were introduced in ES6.

While using the rest parameter, ... (the three consecutive dots) appears on the left side while using spread syntax, ... (the three consecutive dots) appear on the right of the destructuring syntax.

How to Use the Spread Operator in JS?

The Spread operator is defined as an iterable which expands in places where 0+ arguments are expected. It is generally used with variable arrays. It aids us to obtain a list of parameters from an array.

The spread operator is generally used to create a clone of an array.

Note: It doesn’t safely copy multi-dimensional arrays as array values are copied by reference instead of by value.

Example

Output

Explanation of the example

In the above example, we are given an array salad. Now [...salad] will copy the values of the array and assign it to the saladClone. Thus saladCloned has become a copy or a clone of salad.

How to Use the Rest Parameter in JS

The rest parameter syntax allows us to accept an indefinite number of arguments as an array. With Rest Parameter, we can map out the left elements of an array in a new array. The rest parameter must be the last variable in the destructuring syntax.

Example

Output

Explanation of the example

In the above example, we have mapped the first two of the array elements to the tomato and mushroom variables. The remaining elements are mapped to the rest variable using the .... The rest variable is a new array containing the leftover elements.

JavaScript Array Methods

Following are some array methods in Javascript that can be used to manipulate arrays:

concat()

The concat() method is used to merge two or more arrays. This array method in javascript does not change the original arrays but returns the new merged array.

Syntax

Example

Output

every()

The every() array methods in javascript takes a function and checks whether all the elements present in the array pass the logic of the function. It returns a Boolean value, true is returned if the logic holds true for all the elements otherwise, it returns false.

Syntax

Example

Output

forEach()

The forEach() array methods in javascript executes the given function for every element present in the array.

Syntax

Example

Output

join()

The join() array method in javascript joins all the elements of an array and returns a new string separated by a separator. By default, the separator is a comma (,), but we can insert our own separator by passing an argument to the join() method.

Syntax

Example

Output

map()

The map() array methods in javascript takes a function as an argument and returns a new array with the results of the function on every element in the given array.

Syntax

Example

Output

reduce()

The reduce() array methods in javascript executes a user-defined reducer callback function on every element of the array. It returns a value from the calculation on the preceding elements in the array.

Syntax

Example

Output

reduceRight()

The reduceRight() array methods in javascript, similar to the reduce() method, execute a user-defined reducer callback function on every element of the array. It returns the value from the calculation on the preceding elements in the array.

Note: The execution of the reduceRight method happens from right to left.

Syntax

Example

Output

reverse()

The reverse() array methods in javascript is used to reverse the position of all the elements in an array. This method modifies the original array.

Syntax

Example

Output

slice()

This slice() array method in javascript is used to extract a specific portion of an array. It returns a new array with that specific portion and does not change the original array.

Syntax

Example

Output

Using slice() Method with Negative Parameters

As discussed earlier, the parameters of the slice method can be negative. In such cases, the slice method replaces the value of parameters with the value of their sum with the length of the array.

If start is negative then slicing begins from arr.length + start.

If end is negative, then slicing happens till arr.length + end.

Here arr.length is the size of the array.

Example

Output

some()

The some() array methods in javascript take a function and check if at least one element present in the array passes the logic of the function. It returns a Boolean value, true is returned if the logic holds true for at least one element; otherwise it returns false.

Syntax

Example

Output

sort()

The sort() array methods in javascript first convert all the elements of the array into a string and then sort them in ascending order. The elements are sorted in lexicographical order. This method modifies the original array.

Syntax

Example

Output

splice()

The splice() array method in javascript is used to change the content of an array by replacing or removing an existing element and adding a new element at that place.

Syntax

Example

Output

toString()

The toString() array methods in javascript return a string representing the elements of the given array.

Syntax

  • It does not take any parameter.

Example

Output

lastIndexOf()

The lastIndexOf() array methods in javascript, given one argument: a substring to search for, searches the entire calling string and returns the index of the last occurrence of the specified substring.

Syntax

Example

Output

Conclusion

  • An array is a collection of elements of any type or simply a collection of data items stored under a single name.
  • Array in Javascript follows 0-based indexing.
  • Arrays in Javascript are dynamic. We can add or remove elements in the array.
  • Array methods in Javascript are used to manipulate arrays.