Array methods in JavaScript (Part 1)

Array methods in JavaScript (Part 1)

Array methods provide a way of manipulating and working with arrays. In the previous section we talked about 4 of them, array.push(), array.pop(), array.shift() and arr.unshift(...items). Lets see some more of the array methods that exist.

delete

Arrays are objects which means :delete object.key works for arrays.

let abc = ["Alpha", "Beta", "Gamma"];

console.log(abc.length);  //> 3
console.log( abc );       //> [ 'Alpha', 'Beta', 'Gamma' ]

delete abc[1];

console.log(abc.length);  //> 3
console.log( abc );       //> [ 'Alpha', , 'Gamma' ]

However, the problem with delete is, as you can see from the example above, the array still has 3 elements even after delete. This is because it removes the value of the specified key but doesn’t shift elements to the left to fill the hole created. So technically the array still has a length of 3, that is 2 valid elements and 1 hole.

splice

Array.splice() is a very important array method that can do anything from adding, removing to inserting elements. For example we can use splice.(1,1) to delete 1 element from index 1:

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

abc.splice(1,1);

console.log(abc);    //> [ 'Alpha', 'Gamma', 'Delta' ]

The syntax used in the example above is:

array.splice(index, deleteCount);

This means that:

  • array.splice(1,2) deletes 2 elements starting from index 1.
  • array.splice(1,3) deletes 3 elements starting from index 1.
  • array.splice(1,4) deletes 4 elements starting from index 1.
  • array.splice(2,2) deletes 2 elements starting from index 2.
  • array.splice(3,2) deletes 2 elements starting from index 3.
  • array.splice(4,2) deletes 2 elements starting from index 4.
  • etc

With array.splice() you can replace the deleted elements as follows:

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

// delete 2 elements starting at index 1 then replace with "Syd"
abc.splice(1,2, "Syd");

console.log(abc);    //> [ 'Alpha', 'Syd', 'Delta' ]

There is no limit to the number of elements you can insert:

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

// delete 2 elements starting at index 1 then replace with "Syd"
abc.splice(1,2, "Syd", "is", "the");

console.log(abc);    //> [ 'Alpha', 'Syd', 'is', 'the', 'Delta' ]

The syntax is for the example above is:

array.splice(index[, deleteCount, elem1, ..., elemN])

This means that from the position index, delete number of elements equal to deleteCount and then replace with elem1, ..., elemN.

splice returns an array of removed elements:

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

let removed = abc.splice(1,2, "Syd", "is", "the");

console.log(removed);    //> [ 'Beta', 'Gamma' ]

The splice method can also be used to insert the elements into the array without any removals if we set the deleteCount to 0:

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

abc.splice(1,0, "Syd", "is", "the");

console.log(abc);    //> [ 'Alpha', 'Syd', 'is', 'the', 'Beta', 'Gamma', 'Delta' ]

Negative indices are also allowed in array methods. Positive indices specify the position of an element from the beginning of the array, whilst negative indices specify the position from the end.

For example to remove 1 element from the end we use:

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

abc.splice(-1, 1);

console.log(abc); //> [ 'Alpha', 'Beta', 'Gamma' ]

To remove the second element from the end:

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

abc.splice(-2, 1);

console.log(abc);        //> [ 'Alpha', 'Beta', 'Delta' ]

To replace the third element from the end:

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

abc.splice(-3, 1, "C");

console.log(abc);        //> [ 'Alpha','C', 'Beta', 'Delta' ]

slice

The array.slice(start, end) method copies the original array from the start index to the end index exclusive (end element not included) and returns the copy.

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

// copy from index 1 to index 2 exclusive
let a = abc.slice(1, 2);
console.log(a);          //> [ 'Beta' ]

// copy from index 1 to index 3 exclusive
let b = abc.slice(1, 3);
console.log(b);          //> [ 'Beta', 'Gamma' ]

// copy from index 1 to index 4 exclusive
let c = abc.slice(1, 4);
console.log(c);          //> [ 'Beta', 'Gamma', 'Delta' ]

// copy from index 2 to index 3 exclusive
let d = abc.slice(2, 3);
console.log(d);          //> [ 'Gamma' ]

let e = abc.slice(2, 4);
console.log(e);          //> [ 'Gamma', 'Delta' ]

let f = abc.slice(3, 4);
console.log(f);          //> [ 'Delta' ]

// the original array doesn't change
console.log(abc);        //> [ 'Alpha', 'Beta', 'Gamma', 'Delta' ]

Negative indices are allowed and as we stated earlier they count from the end of the array:

let abc = ["Alpha", "Beta", "Gamma", "Delta"];

let a = abc.slice(-3, -1);
console.log(a);          //> [ 'Beta', 'Gamma' ]

The slice method doesn’t change the original array.

concat

The concat method joins the array with other arrays or items.

let oldArr = ["Alpha"];

let newArr1 = oldArr.concat(2);
console.log(newArr1);          //> [ 'Alpha', 2 ]

let newArr2 = newArr1.concat("two");
console.log(newArr2);            //> [ 'Alpha', 2, 'two' ]

let newArr3 = newArr2.concat(["three", "four"]);
console.log(newArr3);            //> [ 'Alpha', 2, 'two', 'three', 'four' ]

console.log(oldArr);             //> [ 'Alpha' ]

This accepts any number of arguments.

indexOf

The array.indexOf(elem, start) looks for an elem starting from index start, and returns the index where the element was found else returns -1 if it is not found.

let avengers = ["Tony", "Steve", "Bruce", "Sam", "James"];

// find Sam
let found = avengers.indexOf("Sam");
console.log(found);                   //> 3

// find Sam starting from index 2
found = avengers.indexOf("Sam", 2);
console.log(found);                   //> 3

// find Sam starting from index 3
found = avengers.indexOf("Sam", 3);
console.log(found);                   //> 3

// find Sam starting from index 4
found = avengers.indexOf("Sam", 4);
console.log(found);                   //> -1

lastIndexOf

The array.lastIndexOf(elem, start) finds the last occurrence of elem searching from start.

let avengers = ["Tony", "Sam", "Bruce", "Sam", "James"];

// first occurence of Sam
let found = avengers.indexOf("Sam");
console.log(found);                   //> 1

// last occurence of Sam
found = avengers.lastIndexOf("Sam");
console.log(found);                   //> 3

includes

The array.includes(elem, start) searches for elem starting from index start, returns true if found and false if not found.

let avengers = ["Tony", "Sam", "Bruce", "Sam", "James"];

// does Bruce exist?
let found = avengers.includes("Bruce");
console.log(found);                   //> true

// does Bruce exist after index 4?
found = avengers.includes("Bruce", 4);
console.log(found);                   //> false

However there is a slight problem with the above mentioned methods and that comes from the fact that comparison of NaN can’t be handled with the === method.

console.log(NaN === NaN);           //> false

Since the indexOf and lastIndexOf methods use the === they handle NaN incorrectly.

let avengers = [NaN, NaN, NaN];

let found = avengers.indexOf(NaN);
console.log(found);                  //> -1

found = avengers.lastIndexOf(NaN);
console.log(found);                  //> -1

found = avengers.includes(NaN);
console.log(found);                  //> true