Array Methods In JavaScript

Arrays have numerous methods to make things simpler, let’s see the example of Array Methods.

Add/remove items

We already have methods for adding and removing items from the beginning and end:

  • arr.push(...items) – adds items to the end,
  • arr.pop() – extracts an item from the end,
  • arr.shift() – extracts an item from the beginning,
  • arr.unshift(...items) – adds items to the beginning.

Here are a few more.

splice

How to remove an element from an array?

We can use Delete, because the arrays are objects.

let arr = ["I", "go", "home"];

delete arr[1]; // remove "go"

alert( arr[1] ); // undefined

// now arr = ["I",  , "home"];
alert( arr.length ); // 3

The element has been removed, but the array still has three elements, as arr.length == 3.

That’s understandable given that delete obj.key removes a value by the key. That is all it does. Perfect for objects. However, in arrays, we usually want the remaining elements to shift and occupy the freed space. We anticipate having a smaller array now.

As a result, special methods must be employed.

The arr.splice method is an array swiss army knife. It has the ability to insert, remove, and replace elements.

Syntax

arr.splice(start[, deleteCount, elem1, ..., elemN])

Starting from the index start, it modifies arr by removing deleteCount elements and then inserting elem1,…, elemN in their place. Returns the array of elements that have been removed.

Examples make this method simple to understand.

Let us begin with the deletion:

let arr = ["I", "study", "JavaScript"];

arr.splice(1, 1); // from index 1 remove 1 element

alert( arr ); // ["I", "JavaScript"]

It removed one element starting at index 1.
In the following example, we remove three elements and replace them with the remaining two:

let arr = ["I", "study", "JavaScript", "right", "now"];

// remove 3 first elements and replace them with another
arr.splice(0, 3, "Let's", "dance");

alert( arr ) // now ["Let's", "dance", "right", "now"]

We can see here that splice returns the array of elements removed:

let arr = ["I", "study", "JavaScript", "right", "now"];

// remove 2 first elements
let removed = arr.splice(0, 2);

alert( removed ); // "I", "study" <-- array of removed elements

The splice method can also insert elements without removing them. To accomplish this, we must set deleteCount to 0:

let arr = ["I", "study", "JavaScript"];

// from index 2
// delete 0
// then insert "complex" and "language"
arr.splice(2, 0, "complex", "language");

alert( arr ); // "I", "study", "complex", "language", "JavaScript"

Negative indexes allowed

Negative indexes are permitted in this and other array methods. They specify the position of the array from the end, as shown here:

let arr = [1, 2, 5];

// from index -1 (one step from the end)
// delete 0 elements,
// then insert 3 and 4
arr.splice(-1, 0, 3, 4);

alert( arr ); // 1,2,3,4,5

slice

The method arr.slice is much easier to use than the similarly named arr.splice.

syntax 

arr.slice([start], [end])

It returns a new array with all items from index start to end copied to it (not including end). When both start and end are negative, the position from the array end is assumed.

It’s similar to the string method str.slice, except it creates subarrays instead of substrings.

Example

let arr = ["t", "e", "s", "t"];

alert( arr.slice(1, 3) ); // e,s (copy from 1 to 3)

alert( arr.slice(-2) ); // s,t (copy from -2 till the end)

We can also call it without any arguments: arr.slice() copies arr. This is frequently used to create a copy for subsequent transformations that should not affect the original array.

concat

The method arr.concat generates a new array that contains values from other arrays as well as new items.

syntax

arr.concat(arg1, arg2...)

It takes any number of arguments, which can be arrays or values.

The result is a new array with items from arr, then arg1, arg2, and so on.

If argN is an array, then all of its elements are copied. Otherwise, the argument is duplicated.

Example

let arr = [1, 2];

// create an array from: arr and [3,4]
alert( arr.concat([3, 4]) ); // 1,2,3,4

// create an array from: arr and [3,4] and [5,6]
alert( arr.concat([3, 4], [5, 6]) ); // 1,2,3,4,5,6

// create an array from: arr and [3,4], then add values 5 and 6
alert( arr.concat([3, 4], 5, 6) ); // 1,2,3,4,5,6

Normally, it only copies array elements. Other objects, even if they appear to be arrays, are added in bulk:

let arr = [1, 2];

let arrayLike = {
  0: "something",
  length: 1
};

alert( arr.concat(arrayLike) ); // 1,2,[object Object]

If an array-like object has the Symbol.isConcatSpreadable property, concat treats it as an array and adds its elements instead:

let arr = [1, 2];

let arrayLike = {
  0: "something",
  1: "else",
  [Symbol.isConcatSpreadable]: true,
  length: 2
};

alert( arr.concat(arrayLike) ); // 1,2,something,else

Iterate: forEach

The foreach method executes a function for every element of the array.

arr.forEach(function(item, index, array) {
  // ... do something with item
});

For example, this displays each array element:

// for each element call alert
["Bilbo", "Gandalf", "Nazgul"].forEach(alert);

This code is more specific about their placement in the target array:

["Bilbo", "Gandalf", "Nazgul"].forEach((item, index, array) => {
  alert(`${item} is at index ${index} in ${array}`);
});

Searching in array

indexOf/lastIndexOf and includes

The methods arr.indexOf and arr.includes have similar syntax and perform the same functions as their string counterparts, but they operate on items rather than characters:

  • arr.indexOf(item, from) – Looks for an item beginning with index from and returns the index where it was found, or -1 if not found.
  • arr.includes(item, from) – Looks for an item beginning with the index from and returns true if it is found.

These methods are typically used with a single argument: the item to be searched. The search is started from the beginning by default.

let arr = [1, 0, false];

alert( arr.indexOf(0) ); // 1
alert( arr.indexOf(false) ); // 2
alert( arr.indexOf(null) ); // -1

alert( arr.includes(1) ); // true

It is worth noting that indexOf compares using the strict equality ===. So, if we search for false, it returns true rather than zero.

If we just want to see if an item exists in the array and don’t need the exact index, arr.includes is the way to go.

The method arr.lastIndexOf is similar to indexOf, but it searches from right to left.

let fruits = ['Apple', 'Orange', 'Apple']

alert( fruits.indexOf('Apple') ); // 0 (first Apple)
alert( fruits.lastIndexOf('Apple') ); // 2 (last Apple)

The includes method handles NaN correctly

A minor but notable feature of includes is that, unlike indexOf:, it handles NaN correctly.

const arr = [NaN];
alert( arr.indexOf(NaN) ); // -1 (wrong, should be 0)
alert( arr.includes(NaN) );// true (correct)

This is due to the fact that includes was added to JavaScript much later and uses a more recent comparison algorithm internally.

find and findIndex/findLastIndex

Consider an array of objects. How do we locate an object that meets the criteria?

The arr.find(fn) method comes in handy here.

let result = arr.find(function(item, index, array) {
  // if true is returned, item is returned and iteration is stopped
  // for falsy scenario returns undefined
});

The function is called for elements of the array, one after another:

  • item is the element.
  • index is its index.
  • array is the array itself.

If true, the search is terminated and the item is returned. If nothing is found, the value undefined is returned.

We have an array of users, for example, with the fields id and name. Let’s look for the one with id == 1:

let users = [
  {id: 1, name: "John"},
  {id: 2, name: "Pete"},
  {id: 3, name: "Mary"}
];

let user = users.find(item => item.id == 1);

alert(user.name); // John

Arrays of objects are common in real life, so the find method is very useful.

Take note that the function item => item.id == 1 with one argument is used in the example. This is common; other arguments to this function are rarely used.

The arr.findIndex method has the same syntax as the arr.find method, but instead of returning the element itself, it returns the index where the element was found. If nothing is found, the value -1 is returned.

The arr.findLastIndex method is similar to findIndex, but it searches from right to left, as lastIndexOf does.

let users = [
  {id: 1, name: "John"},
  {id: 2, name: "Pete"},
  {id: 3, name: "Mary"},
  {id: 4, name: "John"}
];

// Find the index of the first John
alert(users.findIndex(user => user.name == 'John')); // 0

// Find the index of the last John
alert(users.findLastIndex(user => user.name == 'John')); // 3

filter

The find method looks for the first  element that causes the function to return true.

If there are a lot of them, we can use arr.filter (fn).

The syntax is similar to that of find, but filter returns an array of all elements that match:

let results = arr.filter(function(item, index, array) {
  // if true item is pushed to results and the iteration continues
  // returns empty array if nothing found
});

For Example

let users = [
  {id: 1, name: "John"},
  {id: 2, name: "Pete"},
  {id: 3, name: "Mary"}
];

// returns array of the first two users
let someUsers = users.filter(item => item.id < 3);

alert(someUsers.length); // 2

Transform an array

map

One of the most useful and widely used methods is arr.map.

It calls the function for each array element and returns an array of results.

Syntax

let result = arr.map(function(item, index, array) {
  // returns the new value instead of item
});

Example

let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length);
alert(lengths); // 5,7,6

sort(fn)

The call to arr.sort() sorts the array in place, changing the order of its elements.

It also returns the sorted array, but this value is usually ignored because arr is modified.

Example

let arr = [ 1, 2, 15 ];

// the method reorders the content of arr
arr.sort();

alert( arr );  // 1, 15, 2

Note: The items are sorted as strings by default.

For comparisons, all elements are converted to strings. For strings, lexicographic ordering is used, and “2” does indeed outnumber “15.”

To use our own sorting order, we must supply a function as the arr.sort argument ().

The function should perform a comparison of two arbitrary values and return:

function compare(a, b) {
  if (a > b) return 1; // if the first value is greater than the second
  if (a == b) return 0; // if values are equal
  if (a < b) return -1; // if the first value is less than the second
}

Example

function compareNumeric(a, b) {
  if (a > b) return 1;
  if (a == b) return 0;
  if (a < b) return -1;
}

let arr = [ 1, 2, 15 ];

arr.sort(compareNumeric);

alert(arr);  // 1, 2, 15

reverse

Use to reverse the order of elements in arr.

let arr = [1, 2, 3, 4, 5];
arr.reverse();

alert( arr ); // 5,4,3,2,1

After the reversal, it also returns the array arr.

split and join

Syntax : str.split(delim) 

Example

let names = 'Bilbo, Gandalf, Nazgul';

let arr = names.split(', ');

for (let name of arr) {
  alert( `A message to ${name}.` ); // A message to Bilbo  (and other names)
}

The split method accepts an optional second numeric argument – an array length limit. If it is supplied, the additional elements are ignored.

Split into letters

With an empty s, the call to split(s) would split the string into an array of letters:

let str = "test";

alert( str.split('') ); // t,e,s,t

Join

Arr.join() does the opposite of split. It generates a string of arr items

Example

let arr = ['Bilbo', 'Gandalf', 'Nazgul'];

let str = arr.join(';'); // glue the array into a string using ;

alert( str ); // Bilbo;Gandalf;Nazgul

 Summary

A cheat sheet for array methods

 To add/remove elements

  • push(…items) – adds items to the end,
  • pop() – removes items from the end,
  • shift() – removes items from the beginning,
  • unshift(…items) – adds items to the beginning.
  • splice(pos, deleteCount, …items) – at index pos, deleteCount elements are deleted and items are inserted.
  • slice(start, end) – creates a new array and copies elements into it from index start to end (inclusive).
  • concat(…items) – creates a new array by copying all members of the current one and adding new ones. If any of the items is an array, the elements of that array are taken.

To search among elements

  • indexOf/lastIndexOf(item, pos) – search for item starting at position pos, returning the index or -1 if not found.
  • includes(value) – returns true if the array contains a value; otherwise, it returns false.
  • find/filter(func) – use the function to filter elements and return the first/all values that make it return true.
  • findIndex is similar to find, but it returns the index rather than the value.

To iterate over elements

  • forEach(func) – calls func for every element, does not return anything.

To transform the array

  • map(func) – constructs a new array from the results of calling func for each element.
  • sort(func) – sorts the array in place before returning it.
  • reverse() –returns the array after it has been reversed in-place.
  • split/join – convert a string to an array and vice versa.

Submit a Comment

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

Subscribe

Select Categories