15 JavaScript Array Methods You Should Master Immediately (with examples)

Posted by TotalDC

If you want to understand JavaScript arrays but cant’t quite get grips of them, this article will be just what you were looking for.

As you may know, web developers of all skill levels see importance of JavaScript in developing modern websites. JavaScript is so dominant that it is an essential skill to know if you are going to create web apps.

One of the most useful thing built-in to the JavaScript language is arrays. Arrays are commonly found in many programming languages and are used for storing data.

JavaScript includes a lot of array methods. Here are fifteen you should now to grow your skills as a developer.

What Are JavaScript Array Methods?

Array methods are functions in JavaScript that you can apply to your arrays. Each method has a unique function that performs a change or calculation on an array. And that definitely saves you time because you don’t need to code common functions from scratch.

Array methods in JavaScript are run using a dot-notation attached to your array variable. Since they’re just JavaScript functions, they always end with parenthesis which can hold optional arguments. For example here is method attached to a array called myArray.

let myArray = [1,2,3];
myArray.pop();

This code would apply a method called pop to the array.

Array.push()

Method push() takes your array and adds one or more elements to the end of the array, then returns new length of the array. This method will modify your existing array.

Add the number 10 to the array by running push(), using 10 as an argument.

let myArray = [2,4,5,7,9,12,14];
myArray.push(20);

Now you can check if everything worked:

console.log(myArray);

Result should be:

[2,4,5,7,9,12,14,20]

Running the push() method on myArray added the value given in the argument to the end of the array.

Array.concat()

Method concat() can merge two or more arrays into new array. Unlike push() it does not modify existing arrays but creates a new one.

Now let’s take myArray and merge an array called newArray into it.

let myArray = [2,4,5,7,9,12,14];
let newArray = [1,2,3];
let result = myArray.concat(newArray);

And if you would write console.log(result) the result would look like:

[2,4,5,7,9,12,14,1,2,3]

This method is superb when dealing with multiple arrays or values you need to combine, all in one simple step when using variables.

Array.join()

Method join() takes an array and merges the contents of the array, separated by a comma. The result is placed in a string. You even can specify a separator if you want to use an alternative to a comma.

Let’s take a look at how this works using myArray. First using the default method with no separator argument, which will use a comma.

let myArray = [2,4,5,7,9,12,14];

myArray.join();

Result would look like this:

"2,4,5,7,9,12,14"

JavaScript will output a string, with each value in the array separated by a comma. You can use an argument in the function to change the separator.

First let’s say you want string to be separated by space:

myArray.join(' ');

"2 4 5 7 9 12 14"

Or maybe you want something more similar to normal sentence:

myArray.join(' and ');

"2 and 4 and 5 and 7 and 9 and 12 and 14"

Array.forEach()

Method forEach() (forEach() – case sensitive) performs a function on each item in your array. This function is similar to using for loop to apply a function to an array but much easier and less work to code.

Now look at the syntax:

myArray.forEach(function(item){

//code

});

Here foreach() is applied with the dot notation. You place the function you wish to use inside parenthesis wich in the example is function(item).

Take a look at function(item). This is the function executed inside of forEach(), and it has its own argument. We’re calling the argument item.

  • When forEach() loops over your array, it applies the code to this argument. Think of it as a temporary variable that holds the current element.
  • You choose the name of the argument, it can be named anything you want. Typically this would be named something that makes it easier to understand, like “item” or “element”.

With those two things in mind, check out this simple example. Add 5to every value, and have the console show the result.

myArray.forEach(function(item){

    console.log(item + 15);

});

Here we’re using item in this example as the variable, so the function is written to add 15 to each value via item. The console then prints the results. Here’s what it looks like in a Google Chrome console.

The result is every number in the array, but with 15 added to it.

Array.map()

Method map() performs a function on every element in your array and places the result in a new array.

Although it sounds like forEach(), the difference here is that map() creates a new array when used. forEach() does not create a new array automatically.

For example you can use map() to double the value of every element in myArray and place them in a new array. You will see the same function(item) syntax for more practice.

let myArray = [2,4,5,7,9,12,14];
let doubleArray = myArray.map(function(item){

return item * 2;

});

Results in the console would look like this:

console.log(doubleArray);
[4,8,10,14,18,24,28]

And you can see that myArray is unchanged:

console.log(myArray);
[2,4,5,7,9,12,14]

Array.unshift()

Method unshift() works similarly to push(). It takes your array and adds one or more elements to the start of the array (push() adds new elements to the back of the array). This method will modify your existing array.

let myArray = [2,4,5,7,9,12,14];

myArray.unshift(0);

When using console.log(), you should see the number 0 at the start of the array.

console.log(myArray);
[0,2,4,5,7,9,12,14]

Array.sort()

Method sort() is one of the most used operations and you definitely must know it. JS sort() method can be used to sort an array of numbers or even strings with just a single line of code. It returns sorted array by modifying the initial array.

Lets look at example:

let myArray = [12, 55, 34, 65, 10];

myArray.sort((a,b) => a - b);

Since the sorting is done in place, you don’t have to declare a separate variable for the sorted array.

console.log(myArray);

[10, 12, 34, 55, 65]

By default array is sorted in ascending order but you can pass a custom function to sort() method to sort the array in other way.

Array.reverse()

This reverse() method is used to reverse the order of the elements in the array. And now the example:

let myArray = [2,4,5,7,9,12,14];

myArray.reverse()

Log the output to the console to verify the operation.

console.log(myArray);

[14, 12, 9, 7, 5, 4, 2]

As you can see, the order of the elements has been reversed. Previously, the element at the last index (element 14 at index 6) is now the element at the zeroth index and so on.

Array.slice()

Method slice() is used to retrieve a copy of a portion of an array. This method allows you to select specific elements form an array by their index. You can pass the starting index of the element from which you want to retrieve elements and optionally the end index as well.

But what if you don’t provide the end index. Then all the elements from the start index to the end of the array will be retrieved. This method returns a new array and does not modify the existing one.

For example:

let myArray = [2,4,5,7,9,12,14];

let slicedArray = myArray.slice(2);

In the code above, all the elements from the second index to the last index are retrieved since the end index parameter isn’t passed. Log both the arrays to the console.

console.log(myArray);

console.log(slicedArray);

[2, 4, 5, 7, 9, 12, 14]

[5, 7, 9, 12, 14]

The array is not modified by the slice() method and instead returns a new array that is stored in the slicedArray variable. Here’s an example in which the end index parameter is also passed to the slice() method.

let myArray = [2,4,5,7,9,12,14];

let slicedArray = myArray.slice(1, 3);

console.log(slicedArray);

Result:

[4, 5]

Array.splice()

Method splice() is used for removing or replacing elements in the array. By specifying the index and number of elements to delete it modifies the array.

let myArray = [2,4,5,7,9,12,14];

myArray.splice(2, 3);

console.log(myArray);

In the example, the myArray array is spliced from index 2 and 3 elements are removed from it. The array now consists of:

[2, 4, 12, 14]

o replace the elements rather than just deleting them, you can pass any number of optional parameters with the elements you want to replace with, like this:

let myArray = [2,4,5,7,9,12,14];

myArray.splice(2, 3, 1, 2, 3);

console.log(myArray);

Result:

[2, 4, 1, 2, 3, 12, 14]

Array.filter()

Method filter() takes a function containing a test and returns a new array with all the elements that pass that test. This method is used to filter the elements you need from the other elements. The filtration is done using function that returns boolean value.

Here’s an example of the filter() method used for getting only those elements from the array that are divisible by 2.

let myArray = [2,4,5,7,9,12,14];

let divisibleByTwo = myArray.filter((number) => number % 2 === 0);

console.log(divisibleByTwo);

In this example an arrow function is passed as the parameter which takes each number from the original array and checks if it is divisible by using % and === operators. Result of this would look like this:

[2, 4, 12, 14]

Array.reduce()

reduce() is method that takes a reducer function and executes it on each array element to output single value. It takes a reducer function with an accumulator variable and a current element variable as required parameters. The accumulator’s value is remembered across all the iterations and is ultimately returned after the final iteration.

A popular use case of this method is to calculate the sum of all the elements in the array. The implementation of this functionality is:

let myArray = [2,4,5,7,9,12,14];

let sumOfNums = myArray.reduce((sum, currentNum) => sum + currentNum, 0);

0 is passed as the second parameter in the example, which is used as the initial value of the accumulator variable. The sumOfNums variable will contain the return value of the reduce() method which is expected to be the sum of all elements in the array.

console.log(sumOfNums);

Result:

53

Array.includes()

This method is used when you need to know if an element is present in an array. Here’s how you can use it:

let myArray = [2,4,5,7,9,12,14];

console.log(myArray.includes(4));

console.log(myArray.includes(2, 1));

console.log(myArray.includes(12, 2));

console.log(myArray.includes(18));

This method takes a parameter, the element to search for, and third parameter which is optional, the array index from which to start searching from. Depending on that element is present or not, it will return true or false respectively. The result will be:

true

false

true

false

Array.indexOf()

Method indexOf() is used to find out the index at which the first occurrence of and element you are looking for. lthough it is similar to the includes() method, this method returns the numerical index or -1 if the element is not present in the array.

let myArray = [2,4,5,7,9,12,14];

console.log(myArray.indexOf(4));

console.log(myArray.indexOf("4"));

console.log(myArray.indexOf(9, 2));

indexOf() method uses strict equality to check if an element is present, which means that the value, as well as the data type, should be the same. The optional second parameter takes the index to start searching from. The output will look like this:

1

-1

4

Array.fill()

This method is used when for example you need to set all the values in the array to a static value for example 0. Instead of using a loop, you can try fill() method for the same purpose. You can call this method on an array with 1 required parameter: the value to fill the array with and 2 optional parameters: the start and the end index to fill between. This method modifies the exiting array.

let myArray = [2,4,5,7,9,12,14];

let array1 = myArray.fill(0);

myArray = [2,4,5,7,9,12,14];

let array2 = myArray.fill(0, 2);

myArray = [2,4,5,7,9,12,14];

let array3 = myArray.fill(0, 1, 3);

Console log would look like this:

console.log(array1);

console.log(array2);

console.log(array3);
[0, 0, 0, 0, 0, 0, 0]

[2, 4, 0, 0, 0, 0, 0]

[2, 0, 0, 7, 9, 12, 14]

Arrays are a powerful part of the JavaScript language, which is why there are so many methods built-in to make your life easier as a developer. And as you may know the best way to master these fifteen methods is to practice.

Leave a Reply

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

%d bloggers like this: