Most Important Array Methods in JavaScript

Satyapriya Mishra
The Startup
Published in
8 min readAug 29, 2020

Array is a very special concept in any programming language. All the major programming languages support the array data structure. Before going into the technicalities of the array from a programming point of view, let’s try to understand what an array is from a common man’s perspective.

Have you ever seen a school assembly? It is pretty obvious, you have seen it and in childhood all of us have been part of that boring event. In the assembly hall, students of the same class or section sit together in one row, isn’t it. That is a bare minimum real-life example of an array.

Another example could be the color pencil box which all of us have used for coloring pictures. In that pretty little box, the items share something in common. They are all used for giving colors, right. So, in the perspective of programming, we can say array is a collection of items which are related to each other.

The arrangement of the items inside an array leads to a particular structure because of which arrays are called a special type of data structure. The term data structure refers to an arrangement of data in such a way that setting, and retrieval of items is very simple, and they follow a certain pattern.

An array essentially can just contain simple data elements like numbers and strings or in more complex scenarios, they can contain complex objects. In javaScript particularly, arrays are hashtable based and they not necessarily are placed in contiguous memory locations.

JavaScript arrays are index based and we can set and fetch items based on their indices. JavaScript essentially does not support the concept of associative arrays which means it does not fetch or set array items through keys or simple terms strings.

The simplest way to initialize an array in JavaScript is

var arr = [];

If you want to store some items, say some numbers in the array, we can initialize it as follows.

var arr = [1,2,3,4,5];

In case you want to store some objects in the array, it will be like the below code snippet. In this case the array is also known as Array of Objects.

var arr = [ 
{ name: 'Satya', age: 28 },
{ name: 'Priya', age: 24 },
{ name: 'Mishra', age: 23 }
];

JavaScript arrays are zero indexed. What does that mean and why is it so. Let’s see in a while.

Zero indexed simply means that the index of the first element of an JavaScript array starts from 0 just like C and C++.There are other programming COBOL, FORTRAN, R, Julia etc. which do not follow this convention. This happens for JavaScript because of the design of the programming language. When we say we want to access the first element of the array, by design, the first element resides at a place which is referenced by the array variable itself. So here the index is not pointing to the memory position of the element, but rather it points to the offset of the element from the initial memory location pointed to by the variable. Clear, Huh. Now let’s explore some important properties and methods of array data structure in JavaScript.

length

The length property gives the count of the items present in the array. It is a very important property as it is very helpful while iterating over an array. The index of the last item in the array is 1 less than the length.

var arr = [1, 2, 3, 4, 5]; 
console.log(arr.length); // 5

To get the last item we can do like;

arr[arr.length - 1] // 5

For iterating over the array, we can run a for loop through the array with the length property coming in as a condition.

for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

push ():

push method is used to add a new array element at the end of the array. Pretty straightforward. Let’s see the syntax.

var arr = [1,2,3,4,5]; 
arr.push(6);
console.log(arr); // [1, 2, 3, 4, 5, 6]

pop ():

pop method is used to remove the last item from an array. We can even empty an array with this method if we run a loop on the array for a count equal to the length of the array and pop each element from it. The pop() method returns the popped value.

var arr = [1, 2, 3, 4, 5]; 
var len = arr.length;
for (var i = 0; i < len; i++) {
arr.pop();
}

shift ():

The shift () method is used to remove an element from the beginning of an array. It returns the removed element after the operation.

var arr = [1, 2, 3, 4, 5]; 
arr.shift();

unshift ():

The unshift method is used to add a new item at the beginning of the array. It returns the length of the final array.

var arr = [1, 2, 3, 4, 5]; 
arr.unshift(0);

delete ():

The delete method is used to delete an array entry as follows.

var arr = [1, 2, 3, 4, 5]; 
delete arr[2];
console.log(arr); // [1, 2, empty, 4, 5]

It returns a Boolean true or false depending upon if the deletion operation was successfully conducted or not. The deleted item shows as empty in the array and the length of the array remains unaffected. That happens because though there is no item present in the particular memory location, still it gets counted in the length of the array.

splice ():

The splice method removes array items and replaces new items if provided. The syntax of the splice() method is as follows.

splice (starting index to remove item, number of items to remove, replacement items);

The third parameter is optional.

var arr = [1, 2, 3, 4, 5]; 
arr.splice(1, 2);
console.log(arr); // [1, 4, 5]

With replacement items by providing the third parameter, we can remove the item first and replace it with new items.

var arr = [1, 2, 3, 4, 5]; 
arr.splice(1, 2, 9, 10);
console.log(arr); // [1, 9, 10, 4, 5]

If given a negative index, the splice operation is conducted from the end of the array.This method returns a new array containing the removed items.

Slice ():

This method returns a new array containing the specified items except the last index provided.

arr = [1, 2, 3, 4, 5]; 
arr.slice(1, 3); // [2, 3]

concat ():

The concat method merges more than two arrays or values into a single array and returns the new array. The new array is serialized according to the original arrays.

var arr1 = [1, 2]; 
var arr2 = [3, 4];
arr1.concat(arr2); // [1,2,3,4]

The order of the concat operation matters and the sequence changes as demonstrated in the following code snippet.

var arr1 = [1, 2]; 
var arr2 = [3, 4];
arr2.concat(arr1); // [3,4,1,2]

The concat method also takes individual values as arguments like below.

var arr1 = [1, 2]; 
var arr2 = [3, 4];
arr1.concat(arr2, 5, 6); // [1,2,3,4,5,6]

forEach():

The forEach method is used to iterate over an array. It is native to the Array prototype. The advantages of forEach loop above are

  • it has a clear syntax
  • the forEach method keeps the variables from the callback function bound to the local scope
  • the forEach is less error prone

An example of the forEach method is given below.

arr = [1,2,3,4,5];
arr.forEach((item, index) => {
console.log(`${item} is at index ${index}`);
});
// 1 is at index 0
// 2 is at index 1
// 3 is at index 2
// 4 is at index 3
// 5 is at index 4

indexOf ():

This method returns the position of the first occurrence of the item in the array. If the provided item is not part of the array, then it returns -1. Due to this feature, this method is used to check if an item is present in the array.

First let’s check a very simple example.

var arr = [1, 2, 3, 4, 5]; 
arr.indexOf(3); //2

To check if an element is present in the array, we can do like,

var arr = [1, 2, 3, 4, 5];
if (arr.indexOf(item) > -1) {
// Code to be executed when item is present
}

lastIndexOf ():

The lastIndexOf method returns the last occurrence of the item in the array. It essentially searches from the end of the array.

var arr = [1, 2, 3, 4, 1, 6]; 
arr.lastIndexOf(1); // 4

includes ():

This method checks if an item is present in the array and returns a Boolean.

var arr = [1, 2, 3, 4, 5]; 
arr.includes(2); // true

find ():

The find method is used to find a particular item in an array. This method is very useful particularly when you are dealing with an array of objects. We pass a condition for this method and it selects the first element that matches the condition. If no item matches the condition, then it gives undefined.

var students = [ 
{ roll: 1, name: "John" },
{ roll: 2, name: "Pete" },
{ roll: 3, name: "Mary" }
];
var student = students.find(student => student.roll == 2); console.log(student.name); // {roll: 2, name: "Pete"}

findIndex ():

This method returns the index of the found element instead of the entire object and if no item matches the condition, then it returns -1.

var students = [ 
{ roll: 1, name: "John" },
{ roll: 2, name: "Pete" },
{ roll: 3, name: "Mary" }
];
var student = students.find(student => student.roll == 2); console.log(student.name); // 1

map ():

The map () function is used for array transformation. It takes another custom function as an argument and on each array item, applies that function. The function provided as an argument can be a conventional vanilla JavaScript function or it may be an arrow function.

var arr = [1, 2, 3, 4, 5]; 
arr.map(function (item) { console.log(item + 1); });

Sort ():

The sort method as the name suggests is used to sort an array. A simple issue with the sort method is that it sorts the items by their corresponding string ASCII values thereby giving inaccurate results sometimes.

To overcome this problem, we pass a callback function as an argument which compares elements and gives the exact result. A simple use of the sort method is as follows.

arr = [3, 2, 3, 4, 2, 2, 7]; 
arr.sort(function (a, b){ return a - b; });//ascending order sorting

We can also do a descending order of sorting just by reversing the return value of the callback function. An example of a descending order sorting can be as follows.

arr.sort(function (a, b) {
return b - a;
});// descending order sorting

Reverse ():

This method is used to reverse an array. It is a very straightforward method.

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

reduce ():

This method is used to reduce the array into a single value.

function sum(total, num) { 
return total + num;
}
var arr = [1, 2, 3, 4, 5];
numbers.reduce(sum); // 15

isArray ():

This method returns a Boolean stating if the provided variable is an array or not. If the value is an array it returns a true, else it returns false.

var arr = [1, 2, 3, 4, 5]; 
Array.isArray(arr); // true
Array.isArray({}); // false

These are pretty much the mostly needed array methods.

--

--