JavaScript Array Methods

JavaScript Array Methods

In this article, we will cover most of the methods that allow us to manipulate arrays including transforming, searching, and iterating over them.

JavaScript provides a ton of different methods that make it easy to work with arrays. In this article, we will cover most of the methods that allow us to manipulate arrays including transforming, searching, and iterating over them.

Since we'll be working on arrays, I'd expect you to know what arrays are and how they're used. With that said, let's get started!

Add/remove Items from an Array

Four basic methods allow us to add or remove elements from an array:

  • push()

  • pop()

  • unshift()

  • shift()

push() Method

The array.push() method appends items to the end of an array. It accepts a list of items as an argument, and modifies an array by adding the items to the end of it, and then it returns the length of the modified array.

Syntax

array.push(...items);

Example

// define an array
let numbers = [1, 2, 3, 4, 5];

// add 6 to the end of the array.
numbers.push(6);

console.log(numbers); // [1, 2, 3, 4, 5, 6]

// you're not limited to one item
numbers.push(7, 8, 9, 10);

console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In case you don't know how to open the developer console, if you're using Google Chrome, hit the keyboard shortcut Ctrl+Shift+i, or Cmd+Shift+i for Mac.

pop() Method

The array.pop() method removes an item from the end of an array. It returns the item that is removed from the array.

Syntax

array.pop();

Example

// define an array
let numbers = [1, 2, 3, 4, 5];

// removes 5 from the end of the array.
let removedItem = numbers.pop();

console.log(numbers); // [1, 2, 3, 4]

// the items removed from the array
console.log(removedItem); // 5

unshift() Method

The array.unshift() method prepends items to the beginning of an array. It accepts a list of items as arguments, and modifies the array by adding the items to the beginning of it, and then it returns the length of the modified array.

Syntax

array.unshift(...items);

Example

// define an array
let numbers = [1, 2, 3, 4, 5];

// add 0 to the beginning of the array.
numbers.unshift(0);

console.log(numbers); // [0, 1, 2, 3, 4, 5]

// you're not limited to one item
numbers.unshift(-3, -2, -1);

console.log(numbers); // [-3, -2, -1, 0, 1, 2, 3, 4, 5]

shift() Method

The array.shift() method removes an item from the beginning of an array. It returns the item that is removed from the array.

Syntax

array.shift();

Example

// define an array
let numbers = [1, 2, 3, 4, 5];

// removes 1 from the end of the array.
let removedItem = numbers.shift();

console.log(numbers); // [2, 3, 4]

console.log(removedItem); // 1

splice() Method

The array.splice() method is like a replacement for all the four methods mentioned above. It can add and remove elements from the beginning and end of an array, and also at any position in an array. With this method we are not limited to the beginning or end of the array, but rather, we specify the position in the array where we want to add or remove elements.

When this method is used, it returns an array with the items that have been removed from the array.

Syntax

array.splice(index[, deleteCount, elem1, ..., elemN])
  • array is the array which we want to play with.

  • index is the position in the array which we want to remove an element.

  • deleteCount is the number of elements we want to remove from the array.

  • elem1 ... elemN are the elements that are to be added to the array, replacing the removed ones (if that's the case).

Example 1: Removing items from an array.

let names = [  "Joe  ",   "Nina  ",   "Eric  ",   "John  ",   "Farris  "];

// specify position to remove items from, then number of items to remove
let removedNames = names.splice(2, 1);

console.log(removedNames); // [  "Eric  "]

console.log(names); // [  "Joe  ",   "Nina  ",   "John  ",   "Farris  "];
  • The first argument, 2, specifies that we remove items starting with item with index 2, which is the 3rd element in the array: "Eric ".

  • The second argument, 1, specifies that one element be removed from the array. Hence, only the 3rd element, "Eric ", is removed.

Note: If you specify only the first argument, it'll remove items from the specified index, straight to the end of the array. Here's an example:

let ages = [18, 21, 33, 13, 34];

ages.splice(3); // remove elements from index 3 to the end

console.log(ages); // [18, 21, 33]

Example 2: Replacing items in an array.

let names = [  "Joe  ",   "Nina  ",   "Eric  ",   "John  ",   "Farris  "];

// specify position to remove items from, then number of items to remove, and then the new items
let removedNames = names.splice(2, 2,   "Frank  ",   "Bridget  ");

console.log(removedNames); // [  "Eric  "]

console.log(names); // [  "Joe  ",   "Nina  ",   "John  ",   "Farris  "];
  • We specify that we want to start removing items from the 3rd element (index 2).

  • We specify that we want to remove two elements.

  • We replace the removed elements with "Frank " and "Bridget ".

Example 2: Adding elements to an array, without removing any.

When you want to add elements to an array with the splice() method, set the second argument as 0. This "informs " JavaScript to remove zero (or no) elements from the array.

let names = [  "Joe  ",   "Nina  ",   "Eric  ",   "John  ",   "Farris  "];

// specify that no items be removed, by passing 0 as second argument
let removedNames = names.splice(2, 0,   "Frank  ",   "Bridget  ");

console.log(removedNames); // []

console.log(names); // [  "Joe  ",   "Nina  ",   "Frank  ",   "Bridget  ",   "Eric  ",   "John  ",   "Farris  "];
  • You can notice that the statement console.log(removedNames); returns an empty array. This means no elements were removed.

  • After we log names to the console, we realise that the names "Frank " and "Bridget " were added before "Eric ".

slice() Method

The array.slice() method makes of a copy of an array, leaving the original array untouched, unlike the splice() method. If you've ever used the slice() method on strings, you'd know it's similar, except instead of returning a sub-string, it returns a sub-array.

Syntax:

array.slice([start], [end])
  • start is the index from which it starts copying the array.

  • end is the index at which it stops, without copying the item with the end index.

Example

let letters = ['A', 'B', 'c', 'd', 'e', 'F', 'G'];

// copy from item 'c' to 'F', but do not include 'F'
let smallLetters = letters.slice(2, 5);

// here is the copied array
console.log(smallLetters); // ['c', 'd', 'e']

// here is the original array, untouched
console.log(letters); // ['A', 'B', 'c', 'd', 'e', 'F', 'G']

We can also ignore the start and end parameters. When we do that though, the slice() method copies the entire array; which can be later transformed and it'll not have any effect on the original array.

concat() Method

The array.concat() method joins the array on which it was used to other arrays and or values that are passed to it as arguments. It then returns the joined array, leaving the original array untouched.

Syntax

array.concat(arg1, arg2...);
  • arg1 and arg2 could be arrays and or other values (or objects).

Example

let upTo5 = [1, 2, 3, 4, 5];

// adds the array [6, 7, 8, 9, 10] to the upTo5 array & forms a new array
let upTo10 = upTo5.concat( [6, 7, 8, 9, 10] );

console.log(upTo10); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// you can also concat the array with standalone values
let upTo15 = upTo10.concat(11, 12, 13, 14, 15);

console.log(upTo15); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

// you can concat multiple arrays also
let upTo20 = upTo15.concat( [16, 17, 18], [19, 20] );

I believe the code above is well documented. :)

forEach() Method

Traditionally, if we wanted to run a certain logic over all the items in an array we'd use the for loop. Now ES6 has introduced the for..of loop also.

The array.forEach() method accepts a callback function which grabs every item in an array and performs some logic "for each " of them. Hence the name forEach.

Syntax

mainArray.forEach(function(item, index, array) {
  // ... do something with each item
});
  • mainArray is the array whose items are being iterated over.

  • item is the current item.

  • index is the index of the current item in the array.

  • array is the array whose items are being iterated over. It is the same as mainArray.

Example

Say we have an array of names and we wanted to log all of them to the developer console. Here's how we can achieve that:

let names = [  "Joe  ",   "Nina  ",   "Eric  ",   "John  ",   "Farris  "];

names.forEach(function(name, indexOfName, array) {
  console.log(indexOfName, name);
});
  • The callback function passed to the forEach() method takes each name in the names array, along with the indexOfName and the array itself.

When this code is run we get this result:

0   "Joe  "
1   "Nina  "
2   "Eric  "
3   "John  "
4   "Farris  "

The numbers on the left are the indices of each name stored in indexOfName (you can name it however you want), and the names on the right are the items themselves stored in the name (you can name it however you want).

Most of the time you only want the item, so you won't need the indexOfName or the array. Writing them in the code will make them redundant. You can ignore them:

names.forEach(function(name) {
  console.log(indexOfName, name);
});

Or, with ES6 arrow functions:

names.forEach(name => console.log(name));

Our output becomes:

Joe
Nina
Eric
John
Farris

indexOf(), lastIndexOf() and includes() Methods

The array.indexOf(), array.lastIndexOf() and array.includes() methods are used for searching in an array.

1. The indexOf() Method:

This method looks for an item in an array from a specified index and then returns the index of that item in the array. If the item isn't found, it returns the value -1.

Syntax

array.indexOf(item, from);
  • item is the element whose position, in the array, we're looking for.

  • from is the initial position from which we want to search for the item.

Example

Remember, this method returns an index, so it's good to assign it to a variable so it can be used later.

let names = [  "Joe  ",   "Nina  ",   "Eric  ",   "John  ",   "Farris  "];

// find the index of the name   "John  ", from the beginning of the array, hence the 0 index
let johnIndex = names.indexOf(  "John  ", 0);

console.log(johnIndex); // 3

// Try to find index of   "Nina  " from the position 2
let ninaIndex = names.indexOf(  "Nina  ", 2);

console.log(ninaIndex); // -1

// we get -1, meaning   "Nina  " doesn't exist because we try searching from position 2,   "Eric  ", to the end. Clearly, from   "Eric  " to the end,   "Nina  " doesn't exist.

If you want to search for an item from beginning to end, you can just pass only the item to the indexOf() method and ignore the second argument:

let farrisIndex = names.indexOf(  "Farris  ");

console.log(farrisIndex); // 4

2. The lastIndexOf() Method:

This method has the same syntax as and works just like the indexOf() method, except it searches for an item from the right to left of an array, instead of left to right.

3. The includes() Method:

This method looks for an item in an array from a specified index and then returns true if it was found in the array, else it returns false.

Syntax

array.includes(item, from);
  • item is the element whose position, in the array, we're looking for.

  • from is the initial position from which we want to search for the item.

Example

This method returns a Boolean (true or false), so it's good to assign it to a variable so it can be used later.

let names = [  "Joe  ",   "Nina  ",   "Eric  ",   "John  ",   "Farris  "];

// check if   "Ruby  " exists in the names array from the index 1
let rubyExists = names.includes(  "Ruby  ", 1); // false

// use an if..else condition to print something based on whether or not   "Ruby  " exists
if ( rubyExists ) {
  // rubyExists equals true print this
    console.log(  "Ruby exists!  ");
} else {
  console.log(  "Ruby doesn't exist!  ");
}

The result is:

Ruby doesn't exist!

We get this result because we search for "Ruby " in the array names from the index 1, and since it doesn't exist, the includes() method returns the Boolean false which causes the else block to run instead of the if block.

find() and findIndex() Methods

  • The array.find() method finds one item in an array and returns it based on a condition.

  • The array.findIndex() method finds an item but returns the index, in the array, where the item was found, based on a condition.

Note that, both methods find the first item in the array that satisfies a certain condition (we'll see that soon).

Syntax

Both methods have the same syntax:

mainArray.find(function(item, index, array) {
  // if true is returned, item is returned and iteration stops
  // if false is returned, returns undefined
});


mainArray.findIndex(function(item, index, array) {
  // if true is returned, item's index is returned and iteration stops
  // if false is returned, returns undefined
});
  • mainArray is the array whose items are being iterated over.

  • item is the current item.

  • index is the index of the current item in the array.

  • array is the array whose items are being iterated over. It is the same as mainArray.

Example

In this example, we have an array of even numbers. We'll run the find() and findIndex() methods on the array and we'l realise that they both bring only the first match; the rest are ignored.

let numbers = [200, 400, 600, 800, 1000];

// find the return the first even number
let evenNum = numbers.find(function(number) {
  if (number % 2 === 0) return true;
});

console.log(evenNum); // 200

// find the return the index of the first even number
let indexOfEvenNum = numbers.findIndex(function(number) {
  if (number % 2 === 0) return true;
});

console.log(indexOfEvenNum); // 0
  • With the find() method, the first even number, 200 is returned, ignoring the other even numbers. The % is the modulo operator. [I believe you know how it works]

  • With the findIndex() method, the index of the first even number, 0 is returned, ignoring the other even numbers.

  • We ignored the other parameters of the callback function because we didn't need them.

It is important to note that, the find() and the findIndex() methods will return a result once the condition is passed. Immediately one item passes the condition, the result is returned, according to the method used, and the iteration breaks, ignoring the remaining items.

filter() Method

Say we have flour with rocks in it and we wanted to remove the rocks from the flour. We'd use a net which has holes of sizes less than the sizes of the rocks, but bigger than the sizes of the grains of flour. At this point, the only items that can pass through the holes are those which are smaller in size as compared to the sizes of the holes in the net. Hence, the rocks will be filtered out.

The array.filter() method iterates over an array and runs a test on each item in the array. If the test on the item returns true, then that item is retained, if the test returns false the item is filtered out. This method returns an array of items which have passed the test.

So, unlike the find() method, the filter() method doesn't break iteration when one item passes a test, but rather it goes on to test the remaining items till it's done with all of them, and then it returns an array of the items that passed the test.

Syntax

let results = array.filter(function(item, index, array) {
  // if true, item is pushed to results and the iteration continues
  // returns empty array if no item passed the test

return [Boolean]
});
  • We've seen this syntax several times so I won't go over the item index and array parameters in the callback function.

  • [Boolean] is simply the result of a condition, true or false.

  • The results variable is needed because the filter() method is expected to return an array of elements which passed a condition. So, we store that array in the result variable.

Example

In the following example, we have an array of ages. We want ages which are allowed to take part in election; filtering out ages which are below 18. So, ages equal to or greater than 18 will be our resulting array.

let ages = [18, 16, 21, 32, 17, 19, 13];

// grab mature ages only
let matureAges = ages.filter(function(age) {

  // if age is equal to or greater than 18 return true, age passed test
  if (age >= 18) return true;

    // else return false, age isn't mature; couldn't pass test
    else return false;
});

console.log(matureAges); // [18, 21, 32, 19]

We can replace the if..else condition statements with this line:

return age >= 18;

The above code will evaluate and return true or false based on the item.

With arrow functions we can even simplify it better:

let matureAges = ages.filter(age => age >= 18);

Awesome! :D

map() Method

The array.map() method iterates over an array and transforms every item in the array. What this means is that, we use the map() method on an array and return a modified version of its items.

Syntax

let result = mainArray.map(function(item, index, array) {
  // returns the new value instead of item
  return [modified_item];
});
  • The result variable stores the transformed array that is returned by the map() method.

  • mainArray is the array whose items are being iterated over.

  • item is the current item.

  • index is the index of the current item in the array.

  • array is the array whose items are being iterated over.It is the same as mainArray.

  • [modified_item] is the modified item which we want to return.

Example

In the following example, we take an array of towns in Ghana and then we capitalize all of them.

let towns = [  "accra  ",   "kumasi  ",   "tamale  ",   "koforidua  ",   "sunyani  "];

// ignoring the other parameters since we don't need them
let capitalizedTowns = towns.map(function(town){
  return town.toUpperCase();
});

console.log(capitalizedTowns); // [  "ACCRA  ",   "KUMASI  ",   "TAMALE  ",   "KOFORIDUA  ",   "SUNYANI  "]

reverse() Method

As the name goes, the array.reverse() method reverses the order of items in an array. So, if we had items from A to Z, the reverse() method will make the order Z to A.

Syntax

array.reverse();

Example

let numbers = [1, 2, 3, 4, 5];

// reverse the order of numbers in the array
numbers.reverse();

console.log(numbers); // [5, 4, 3, 2, 1]

join() Method

The array.join() method takes all the items in an array and glues them together, returning a string.

Syntax

array.join(adhesive);
  • array is the array whose items are to be joined.

  • adhesive is what you intend to use to to join the items in the array.

Example

let names = [  "Joe  ",   "Nina  ",   "Eric  ",   "John  "];

// join the names with a comma (,) and then a space
let namesStringWithSpace = names.join(', ');

// Here we realise the items are joined with (  ",   ")
console.log(namesStringWithSpace); // Joe, Nina, Eric, John

// join the names without an   "adhesive  "
let namesStringNoSpace = names.join();

// JavaScript automatically join them with   ",  "
console.log(namesStringNoSpace); // Joe,Nina,Eric,John

reduce() Method

The array.reduce() method is used to calculate a single value based on the elements in an array. It returns a value after the calculation.

Say we have an array shoppingCart which has products, with prices, in it, and we want to find the sum of the prices of the products in the shoppingCart array; array.reduce() can do that.

Syntax

let value = array.reduce(function (accumulator, item, index, array) {
  // ...
return [calc]
}, [initialValue]);
  • The callback function is run on all array elements one after another and “carries on” its result to the next call (or iteration);

  • accumulator is the result of the previous function call. If it is running for the first time, its value is the initialValue (i.e. if the initialValue is provided).

  • item is the current array item.

  • index is its position in the array.

  • array is the array being iterated over.

  • [calc] is the result from the calculation that "reduces " the array to one value.

So, the first argument, accumulator in this case, is the variable that stores the combined result of all previous calculations. When calculation is finished, it becomes the final result to be returned by the reduce() method.

Example

let numbers = [1, 2, 3];

// calculate the sum of all numbers in the numbers array
let total = numbers.reduce(function (sum, currentNumber) {
  return sum + currentNumber;
}, 0);

console.log(total); // 6
  • In the example above, the accumulator is named sum and the item being currently iterated over is named currentNumber.

  • The inital value of sum is set to 0 because the initialValue, after the callback function block, is set to 0.

  • On the first call, the currentNumber has a value of 1 (from the array), and the sum has a value of 0 because of the initialValue. They're both added: sum + currentNumber, resulting to 0 + 1 = 1, and then returned.

  • On the second call, the currentNumber has a value of 2 (from the array), and the sum has a value of 1 because the previous iteration returned a an answer of 0 + 1 = 1. They're both added: sum + currentNumber, resulting to 1 + 2 = 3, and then returned.

  • On the third call, the currentNumber has a value of 3 (from the array), and the sum has a value of 3 because the previous iteration returned a an answer of 1 + 2 = 3. They're both added: sum + currentNumber, resulting to 3 + 3 = 6, and then returned.

The Static Array.isArray() Method

When you use the unary operator typeof to check the data type of an array you get "object ". And if you check for the data type of usualy objects too, the result is the same: "object ". Weird, right?

This is because in JavaScript, arrays are based on objects. So, using the typeof operator will not distinguish between arrays and plain objects.

The static Array.isArray() method allows you to check whether or not a value, passed to it, is an array. It is called a static method because you cannot use it on instances of the Array class, except on the Array class itself.

Syntax

let result = Array.isArray(value);
  • result will store a Boolean (true or false). If true, the value is an array, if false it's not an array.

Example

let numbers = [1, 2, 3, 4, 5];

// pass the array to the isArray method
console.log( Array.isArray(numbers) ); // true

let name =   "Asamoah Gyan  ";
console.log( Array.isArray(name) ); // false
  • The first console.log() statement returns true because the numbers variable passed to the Array.isArray() is indeed an array.

  • The second however, returns false because a string name was passed to it, not an array.

Note that, if you try to use the isArray() method on any array, JavaScript will throw an error:

let numbers = [1, 2, 3, 4, 5];

console.log( numbers.isArray() );

Here's the error:

Uncaught TypeError


I've excluded the methods below to avoid making the article lengthier than it already is. Try as much as possible to refer to them on MDN:


Thanks for reading.