Sign In
Sign In

JavaScript Array Methods

JavaScript Array Methods
Hostman Team
Technical writer
JavaScript
27.11.2023
Reading time: 12 min

Arrays in JavaScript are a data structure that stores various elements, often of the same type. Their main feature is storing multiple values in a single variable. Thanks to their integrated methods and properties, you can add, delete, process, or search the data based on your needs. 

All array values are elements. In turn, they have their own index. Variables can be either of the same or different data types, allowing you to organize more complex data structures.

Creating an array

There are two ways to initialize an array:

1. Using a literal syntax.

In this case, elements are listed inside square brackets and separated by commas. 

const ExampleArr = [element0, element1, …, elementN];

2. using the Array() constructor.

Syntax:

const ExampleArr = new Array(element0, element1[, …[, elementN]]);
const ExampleArr = new Array(arrayLenght);

In both methods, we pass elementN as parameters. These are the variables that create the set of ExampleArr values. ArrayLength is the number of elements. Their default value is not defined. 

After creating the array, let’s fill it in. Let's create a set of values that stores employees' names.

Using the first method:

var EmployeeArr = [‘Alex’, ‘Bob’, ‘Oliver’];

Using the second one:

var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);

Access to array elements 

To access an array element, we use square brackets with an integer value of its index inside them.

Let's get the value of two elements of the previously created value set EmployeeArr:

var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);
console.log (EmployeeArr[1]); 

The index numbering starts from 0, which we should remember when referring to the N-th element. Its index will be N-1. In our case, it will equal 1.

To change the value of an element, you need to assign a new value to the variable, as shown below:

var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);
EmployeeArr[1] = ‘Jack’;

Now EmployeeArr contains 'Alex', 'Jack', and 'Oliver.'

Now let's look at length, an important property that returns the length of an array in JavaScript.

var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);
console.log (EmployeeArr.length); 

The length of EmployeArr in our case will be 3.

-

Array methods

Array methods in JavaScript allow developers to work with data more efficiently and conveniently. Their use will help with conversion, sorting, searching, adding or removing elements. 

In this article, we'll look at most of the existing JavaScript array methods, grouped by their work logic.

Adding and removing elements

There are four main methods to add or remove elements from an array: push(), pop(), shift(), and unshift().

  • push() adds one or more elements to the end of the value set.

  • pop() deletes the last element.

  • shift() deletes the first element.

  • unshift() adds one or more elements to the beginning.

Let's look at examples. We'll indicate the output of each method in the comment.

var arr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);
arr.push (‘Jack’); // ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’
arr.unshift (‘Jacob’, ‘George’); //; ‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’
arr.pop (); // ‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’
arr.shift (); // ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’

The pop() and shift() methods return the value of the deleted element, while push() and unshift() return the length of the modified array.

In addition to the above methods, we should mention the universal splice() method. It allows you to insert, delete, or replace elements.

Syntax of the splice() method:

array.splice(startIndex, deleteCount, element1, element2, ...);

Parameters: 

  • startIndex is the index where the splice should begin. If this parameter exceeds the array length, the startIndex value will equal the length or take the difference between array.length and this number if a negative number is entered. 

  • deleteCount is the number of elements to delete starting from startIndex. It can be equal to 0. In this case, nothing happens. 

  • element1, element2, .... are the elements we add to the array (optional parameter).

The splice() method returns the set of deleted values.

In the example, let's look at several ways to apply splice(). The comments will specify the set of values after the method is executed.

Below, we will remove two elements, starting with 3:

var Dog = new Array(‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Corgi’, ‘Dachshund’, ‘Dalmatian’);
Dog.splice ( 2, 2 ); // ‘Beagle’, ‘Boxer’, ‘Dachshund’, ‘Dalmatian’

Now let's remove one element starting at 4 and add 'Doberman':

var Dog = new Array(‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Corgi’, ‘Dachshund’, ‘Dalmatian’);
Dog.splice (3, 1, ‘Doberman’); // ‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Doberman’, ‘Dachshund’, ‘Dalmatian’

Iterating through an array

The forEach() method is responsible for iterating array elements.

arr.forEach(function callback(currentValue, index, array), thisValue);

Parameters:

  • callback is the main parameter, namely the callback function that will be executed once for each element. Its arguments are currentValue, index, array.

  • currentValue is the element to be processed in the set.

  • index is this element's index.

  • array is the array of the selected element.

  • thisValue is an optional parameter. It takes the value used as this when calling the function.

The returned value is always undefined.

Here are two examples: one using thisValue and one without it.

The example without thisValue parameter:

var Dog = new Array(‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Corgi’, ‘Dachshund’, ‘Dalmatian’);
var NewDog = [ ];
Dog.forEach (function (element) {
NewDog.push (element);
})

The result will be a new set of NewDog values that completely replicates Dog.

Example with the thisValue parameter:

var numbers = [1, 2, 3, 4, 5];
var doubleNumbers = [ ];
var myObject = {
    double: function(element) {
        return element * 2;
    }
};

numbers.forEach (
    function (element) {
        doubleNumbers.push(this.double(element)); 
    }, myObject
);

The result is a doubleNumbers set, which consists of numbers multiplied by two.

Searching for an element in an array

Such methods as indexOf(), lastIndexOf(), includes(), find(), findIndex(), and filter() help to search for items. 

The indexOf() and lastIndexOf() methods search for the required value among all the elements and return its index at the first match. The former searches from the beginning of the array, while the latter searches from the end. Both methods will return -1 if the searched value is not found.

Syntax of indexOf() and lastIndexOf() methods:

array.indexOf( searchElement, fromIndex )
array.lastIndexOf( searchElement, fromIndex )

The searchElement parameter is the same in both cases. It is the element we need to find. This is not the case with the fromIndex parameter. This is the starting index of the element to search for. When indexOf() is used, the fromIndex parameter defaults to zero. In the lastIndexOf() method, it is equal to array.length

Let's try using these methods in the example below. 

var Employee = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘George’, ‘Oliver’, ‘Jack’);
Employe.indexOf (‘George’);
Employe.lastIndexOf (‘George’);

The result of the indexOf() method will be 1 because the first match occurred with an element whose index is 1. In the case of lastIndexOf(), the result will be 3.

The next search method is includes(). It determines whether the set of values contains a certain element, returning true or false depending on the result.

The syntax of the includes() method:

array.includes(searchElement, fromIndex)

The parameters are exactly the same as in the previously discussed indexOf() and lastIndexOf() methods. The only difference between them is the return value. The fromIndex parameter is 0 by default.

Here's an example of using the includes() method:

var Employe = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);
Employe.includes (‘Alex’);
Employe.includes (‘Jacob’, 3);

The result in the first case will be true. In the second case, false.

In practice, JavaScript often uses arrays of objects. In this case, you should search using the find() and findIndex() methods.

arr.find(function callback(currentValue, index, array), thisValue); 
arr.findIndex(function callback(currentValue, index, array), thisValue); 

Parameters of find() and findIndex() methods are similar to forEach(), so you can find their descriptions above.

Let's look at an example of using the find() and findIndex() methods:

var Employee = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);
Employee.find (element => element == ‘Jacob’);
Employee.findIndex (element => element == ‘Jacob’);

The return value of the find() method is 'Jacob', and of the findIndex() method is 0.

The find() and findIndex() methods are suitable for searching one object. If the task is to find several objects, we can use another method: filter()

Syntax of the filter() method:

var filteredArray = arr.filter(function(currentValue, index, array), thisValue); 

The parameters of this method are also similar to the parameters of the forEach() method.

Let's try it. Here we will search for employees who have worked in the company for less than two years:

var Employee = [  
{name: “Jacob”, experience: 3},
{name: “George”, experience: 1},
{name: “Alex”, experience: 1},
{name: “Bob”, experience: 4}
];

var result = Employee.filter(element => element.experience <2);

The method will result in a new array consisting of two employees with less than two years of experience.

Methods for converting arrays

The last group of array methods in JavaScript that we will describe in this article are array transformation methods. These include map(), flat(), flatmap(), sort(), and reverse(). Let's look at each of them in more detail below.

map() organizes a new set of values with the result of calling the specified callback function for each element.

The syntax of the map() method:

var newArray = array.map(function(currentValue, index, arr), thisValue); 

Once again, we see the same parameters as in the previously discussed methods.

The return value of this method will be a new array with the elements of the callback function result.

Let's consider the example that we already used earlier with forEach(), where all the set data were doubled. Now, let's use map() instead of forEach().

var numbers = [1, 2, 3, 4, 5];
var doubleNumbers = numbers.map( 
    function double( element ) {
        return element * 2;
    }
);
console.log(doubleNumbers);

The result is doubleNumbers, a new set of values consisting of numbers 2, 4, 6, 8, 10. 

When we use the map() method, the number of lines of code is noticeably reduced compared to forEach(). Also, the forEach() method is used only for iteration and returns nothing. map() returns a new array of the same length as the original array.

Flat() allows you to interact with a nested set of values. It returns a new array with all sub-array values merged into it recursively  up to the specified level.

The syntax of the flat() method:

var newArray = arr.flat(depth);

Here, depth specifies the level, i.e. how deep a nested array structure should be flattened. If the nesting depth is unknown, you can set the value of the parameter as Infinity. By default, it is equal to one.

Let's consider an example of using the flat() method:

var arr = [1, 2, , [4, 5, [6, 7]]];
var NewArr = arr.flat(Infinity);

The result is NewArr [1, 2, 4, 5, 6, 7]. It is worth noting that one was missing in the set of arr values. The flat() method removed the empty slots.

We can combine the previous two methods into one: flatmap()

The syntax of the flatmap() method:

var new_array = arr.flatMap(function callback(currentValue, index, arr), thisValue)

Here is an example of using flatmap():

var arr = [[1], [2], [3], [4], [5]];
var NewArr = arr.flatMap(element => element * 2);

The result will be NewArr [2, 4, 6, 8, 10].

The sort() method allows sorting the data set. The default sorting order corresponds to the order of Unicode code characters.

Syntax of the sort() method:

array.sort(function(firstValue, secondValue)); 

You can specify a function that determines the sort order as a parameter.

Example:

var EmployeeArr = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);
EmployeeArr.sort ();

The result of sorting will be EmployeArr ['Alex', 'Bob', 'George', 'Jack', 'Jacob', 'Oliver'].

The reverse() method is also worth mentioning. 

Syntax of the reverse() method:

array.reverse();

In the example, let's change the order of employees’ names in the previously sorted array.

var EmployeeArr = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);
EmployeeArr.sort ();
var reversed = EmployeeArr.reverse();

The result of the reverse() method is EmployeArr ['Oliver', 'Jacob', 'Jack', 'George', 'Bob', 'Alex'].

Conclusion

This article has covered the basic, but not all, array methods in JavaScript. It is not easy to memorize them all at once. But it will become easier with experience in solving problems and using the methods in code. The main thing is to memorize how they work and what they are used for, and if necessary, you can always refer to this article to remember the syntax or see examples.

JavaScript
27.11.2023
Reading time: 12 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us
Hostman's Support