Javascript Array Methods
**
Introduction
**
An array is one of the most powerful data structures in JavaScript. When data has to be stored in an ordered manner, an array is the most suitable choice. What makes JavaScript arrays more powerful is the set of available in-built functions using which working with arrays gets a lot easier. Array methods might be intimidating to understand at first. But, not to worry, through this tutorial we will learn important JavaScript array methods and hopefully make the learning process a little less challenging.
There are a few operations that you may want to implement on an array. for eg. insertion, deletion, copying, concatenating two arrays, searching. In JavaScript, there are multiple methods available for each of these operations.
Understanding by categorizing the long-list of JavaScript array methods is a great way to understand these built-in methods. So, let’s dive into these categories and understand what each method in that particular category does.
**
Insert/Delete Elements
**
- push() — adds an element at the end of the array. After insertion, it returns the new length of the array.
let fruits = ["Apple","Banana","Orange"];
fruits.push("Grapes");
console.log(fruits); // [ 'Apple', 'Banana', 'Orange', 'Grapes' ]
- pop()— removes and returns the last element of the array.
let fruits = ["Apple","Banana","Orange"];
fruits.pop();
console.log(fruits); // [ 'Apple', 'Banana' ]
- unshift() — adds an element at the start of the array. Returns the new length of the array after insertion.
let fruits = ["Apple","Banana","Orange"];
fruits.unshift("Pear");
console.log(fruits); //[ 'Pear', 'Apple', 'Banana', 'Orange' ]
- shift() — removes and returns the first element of the array.
let fruits = ["Apple","Banana","Orange"];
fruits.shift();
console.log(fruits); //[ 'Banana', 'Orange' ]
**
Iterate
**
- foreach() method iterates over all elements and implements a given function on each element. It is very often used when an operation has to be performed on each element of the array.
//An array of subjects
let subjects = ["Literature", "Social Science", " Music", "Polity" ];
//item => console.log(item) is an arrow function which prints every item
//for every element present in the array
subjects.foreach(item=>console.log(item));
//Literature
//Social Science
//Music
//Polity
**
Copying/Concatenating
**
slice() method is used to make a copy of an array. It returns a completely new copy of the array “arr” when called as arr.slice(). However, it can also be used to extract a few elements of the array between a specified interval. The syntax for this operation is as follows:
arr.slice(start, end);
It returns a new array copying to it elements in the original array from the index start to index end-1.
//an array of names
let names = ["Rahul", "Raj", "Varun", "Akshay", "Tarun"];
//names stores array returned by slice()
let names1 = names.slice();
console.log(names1); //['Rahul', 'Raj', 'Varun', 'Akshay', 'Tarun'];
//get elements present in array names from index 1 to 3
let names2 = names.slice(1,4);
console.log(names2); //['Raj', 'Varun', 'Akshay']
- concat() method is used to concatenate new elements to an already existing array. If it’s called on an existing array arr as arr.concat(arr2), it returns a new array containing all the elements of arr and arr2. Either a complete array or simply the values to be added in the original array can be passed as the argument to the concat() method.
//an array of names
let names = ["Rahul", "Raj", "Varun"];
//another array of names
let names2 = ["Akshay", "Tarun"];
//concats elements in array names and array names1 in 'newNames'
let newNames = names.concat(names2);
console.log(newNames); //['Rahul', 'Raj', 'Varun', 'Akshay', 'Tarun']
**
Searching in an Array
**
- includes() searches for a given item in the array. It returns true if the item is found and false otherwise. It can either be called as arr.includes(item) or arr.includes(item, from). In the latter case, the method begins its search from the given index from.
let arr = [1, 2, 3, 4, 5];
//check if arr includes 3
console.log(arr.includes(3)); //true
//returns true because 3 is present at index 2
//check if arr includes 3 at or after index 3
console.log(arr.includes(3,3)); //false
//returns false because 3 doesn't exist at index 3 or after it
- indexOf() method is used to find the first index at which a given item occurs in an array. The item for which the index has to be found is passed as an argument. It returns the index if the element is found and -1 otherwise.
let arr =[1, 2, 3, 4, 4, 5];
//returns the first index at which 4 is present in the array
console.log( arr.indexOf(4)); //3
- lastIndexOf() method works the same as indexOf(), however, it finds the last occurrence of the given element. It starts the search from the end of the array and hence returns the last index at which the given element is present in the array.
let arr = [1, 2, 3, 4, 4, 5, 4 ];
//returns last index at which 4 is present in the array
console.log( arr.lastindexOf(4)); //6
- find() array method as the name suggests finds a given element in the array. But, includes(item) does the same, then why do we need find()? Suppose we have an array of objects, and we need to search an object based on a particular property. What’s the way to do that? Here is where find() comes into play!
A callback function is passed as an argument to find(). This function is called for each element/object in the array and is used to search for the required object. Below is an example demonstrating the same
an array of objects
students = [
{
name: "Raj",
age: 20
},
{
name: "Rahul",
age: 23
},
{
name: "Akshay",
age: 28
}
];
//suppose we want to find age of the student named 'Rahul'
//find() will be implemented as follows:
//1. find() calls findAge() checks if the current object's name is 'Rahul'
//2. findAge() checks if the current object's name is 'Rahul'
//3. findAge() returns true, when object with name 'Rahul' is encountered
//4. find() stops the iteration and returns current object
//5. .age is used to get the age of returned object
let age = students.find(findAge).age;
console.log(age); //23
function findAge(student){
return students.name === "Rahul";
}
- findIndex() is used to get the position at which a given element is present in the array. It returns the index if the element is found and -1 otherwise. Moreover, it works pretty much the same as find() method in the sense that it also uses a callback function to search an element.
// an array of objects
an array of objects
students = [
{
name: "Raj",
age: 20
},
{
name: "Rahul",
age: 23
},
{
name: "Akshay",
age: 28
}
];
// suppose we want to find index at which student named "Akshay" is present in the array
//findIndex() will be implemented as follows:
//1. findIndex() calls fn() for each object in the array
//2. fn() checks if the current object's name is "Akshay"
//3. fn() returns true, when object with name "Akshay" is encountered
//4. findIndex() stops the iteration & returns position of current object
let res = students.findIndex(fn);
console.log(res); //1
function fn(student){
return student.name === "Akshay";
}
- filter() performs a check on the array elements and returns a whole new array consisting of elements for which the provided callback function returned true.
//an array of numbers
numbers = [20, 25, 30, 35, 40 ,45];
//filter() calls Evenfn() for each number
//every number for which Evenfn() returns true gets stored in the array even
console.log(even); // [20, 30, 40 ]
//callback function provided to filter()
function Evenfn(item){
return item % 2 === 0;
}
Well, that might be a lot of information to grasp at once for you, but keep going we got a lot more to cover!
**
Array Transformation
**
- map() method is one of the most useful JavaScript array method. It takes a function as an argument and then calls the same function for each array element. It then returns the results in an array.
//an array of integers
let values = [2, 3, 4, 5, 6];
//map() calculates the square of each element using arrow function as argument
let squares = values.map(item=>item*item);
console.log(squares); //[4, 9, 16, 25, 36]
- sort() method as the name suggests sorts an array. No doubt, it is one of the widely used array methods in JavaScript. It sorts the array in place.
//an array of integers
let values = [7,8,15,11,2];
//sorts the "values" array
values.sort();
console.log(values); //[11, 15, 2, 7, 8]
- reverse() method reverses the order of elements present in an array. It performs reversal in-place.
//an array of integers
let values = [2, 3, 4, 5, 6];
//reverses the order of elements present in array "values"
values.reverse();
console.log(values); //[6, 5, 4, 3, 2]
splice() - All in one The splice() method is the most powerful array method. It can do everything from insertion, deletion, replacement of elements in an array. Moreover, it can perform these operations at any given position — start, mid, or at the end. Amazing right? It’s time to unveil the power of splice() method now!
Its syntax is as follows:
arr.splice(start, deleteCount, item1, item2, item3,…)
Here, start is the index starting at which operation is to be performed, deleteCount represents the count of elements to be deleted and item1, item2, item3 are elements to be inserted. Note that it’s not always necessary or mandatory to call splice() with all the arguments, therefore, it can be called based on the requirements.
Here’s an example of how to insert elements in an array using splice().
//a shopping List array
let ShoppingList = ["Eggs", "Almond milk", "Bread", "Bananas"];
//from index 0
//delete 0 elements
//and insert "Spinach", "Sugar"
shoppingList.splice(0, 0, "Spinach", "Sugar");
console.log(shoppingList); //[ 'Spinach', 'Eggs', 'Almond Milk', 'Bread', 'Bananas']
//a shopping List array
let shoppingList = ["Eggs", "Almond Milk", "Bread", "Bananas"]
//from index 2
//delete 0 elements
//and insert "Butter"
shoppingList.splice(2, 0, "Butter");
console.log(ShoppingList);
The following example shows how to delete elements in an array using splice().
let arr = ["This", "Blog", "is", "about", "Javascript", "Array", "Methods"];
//from index 2 delete 2 elements
arr.splice(2,2);
console.log(arr); // ['This', 'blog', 'Javascript', 'Array', 'Methods'];
Not only can we do insertion, deletion using splice() but replacement operation can be performed too.
//an array of subjects
let subjects = [''Literature'', "History", "Geography", "Polity"];
// from index 1 delete 2 elements
//and insert "Maths", "Programming"
subjects.splice(1,2,"Maths", "Programming");
console.log(subjects); // ['Literature', 'Maths', 'Programming', 'Polity']
With this, we have reached the end of this JavaScript array methods tutorial. We covered the commonly used methods for performing operations such as insertion, deletion, transformation, copying, concatenation, and searching.