Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Array in JavaScript
2.1.
Creating an array in JavaScript
3.
Array Methods
3.1.
of() method
3.2.
indexOf() method
3.2.1.
Special Case 1 (Searching from a specified position)
3.2.2.
Special Case 2 (Searching from the end)
3.3.
length() method
3.4.
find() method
3.5.
findIndex() method
3.6.
reverse() method
3.7.
forEach() method
3.8.
concat() method
3.9.
join() method
3.9.1.
What if we want to join without any characters or commas?
3.10.
map() method
3.11.
flat() method
3.12.
pop() method
3.13.
push() method
3.14.
filter() method
3.15.
sort() method
3.16.
shift() method
3.17.
unshift() method
3.18.
slice() method
3.19.
toString() method
4.
Frequently Asked Questions
4.1.
What is an array?
4.2.
Why do we need arrays?
4.3.
How to join elements of the array without any characters or commas?
4.4.
How to start searching for an element from a specified index?
4.5.
What does the unshift method return? 
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Array Methods in Javascript

Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Hey Ninjas, have you ever thought about why we need arrays? It would have been very tough to store every element individually, especially when we have so many of them. Array in JavaScript help us to tackle this problem. Moreover, many different JavaScript methods make the operations of the array easier.

Array methods in Js

In this article, we’ll get to know some of the essential Javascript functions with the help of examples. So, let’s get started!

Array in JavaScript

Array in js

We use an array when we store more than one value in one object. We can define an array as a single object that stores multiple values in a list. Thus, we also call them "list objects." For better understanding, we can assume it is a container storing numerous values. We can store and treat the array objects the same way as any other type of value in variables, the only difference being that we can access each value in the array separately. Now, after knowing what an array is, let us learn to make an array in JavaScript. 

Also See, Javascript hasOwnProperty

Creating an array in JavaScript

To know how to create an array, we must know the syntax first. The syntax for writing an array is 

const array_name = [value1, value2, ...];    


Let us see an example of how we create an array in JavaScript.

We can create an array and then provide its elements, or we can directly declare an array along with the elements.

// Creating array first, then providing elements to it.
const arr1 = [];
arr1[0]  = "Be";
arr1[1]  =  "a";
arr1[2]  = "Coding";
arr1[3]  = "Ninja";

// Creating array along with elements.
const arr2 = ["Be", "a", "Coding", "Ninja"];

// Logging arr1 and arrr2
console.log(arr1) ;
console.log(arr2) ;


Output:

Output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Array Methods

Many useful JavaScript functions help us to perform different works in an array. Some of the widely used methods are described below:

of() method

First, we will start with knowing a method we can use to create an array. This can be another way to create an array other than the above-mentioned ones. This method will create an array instance of all the elements in the argument.

// Creating an array str with elements Be, a, Coding, Ninja
let str = Array.of("Be", "a", "Coding", "Ninja");

// Logging str
console.log(str);

 

Output:

Output

indexOf() method

After the creation of the array, we now require to know the position of certain elements in the array. For this purpose, we use the indexOf() method. 

// Creating array along with elements.
const arr = ["Be", "a", "Coding", "Ninja"];

// Writing the answer function.
const answer = arr.indexOf("Ninja");  

// Logging the answer
console.log("\'Ninja\' is present at index = " + answer);

 

Output:

Output

Special Case 1 (Searching from a specified position)

In this method, we can specify the position from where we want to look onwards. So, we will search only from our specified position and not from the beginning. The syntax for the same is as follows.

const answer = arr_name.indexOf("element_to_searched", index);

The index in the above code is the position from where we will start searching.

Special Case 2 (Searching from the end)

In this special, we want to search from the end; that is, we want to start from the last index and go to the left-hand side to search for the element. The method we use for this is the lastIndexOf() method. The syntax is as follows.

const answer = arr_name.lastIndexOf("element_to_searched");

length() method

We use this method to know the length or the number of elements in the array. 

// Creating array along with elements.
const arr = ["Be", "a", "Coding", "Ninja"];

// Logging the length
console.log("The length of the array is " + arr.length);

 

Output:

Output

find() method

We use this method for returning the first found element in the array, which satisfies the given condition. If anyone of the element satisfies the conditions, we get it as an answer, or else we get undefined as the answer.

// Creating array along with elements.
const arr = ["1800", "123", "3598"];

// Writing the answer function
const answer = arr.find(x => x<200);  

// Logging the answer
console.log("ans = " + answer);

 

Output:

Output

findIndex() method

We just learned about a method that returns the first element satisfying our conditions. What if we need its index? For this purpose, we have a method named the findIndex() method since this method returns the index of the first element that satisfies the condition.

// Creating array along with elements.
const arr = ["1800", "123", "3598"];

// Writing the answer function
const answer = arr.findIndex(x => x<200);  

// Logging the answer
console.log("index of ans = " + answer);

 

Output:

Output

reverse() method

We use to method to invert the order of the elements in the array.

// Creating array along with elements.
const arr = ["Be", "a", "Coding", "Ninja"];

// Writing the answer function
const answer = arr.reverse();  

// Logging the answer
console.log("Reversed array : ");
console.log(answer);

 

Output:

Output

forEach() method

When we want to perform a function once on every element of the array, we use the forEach() method.

/* 
    Creating array along with elements.
    Assuming the initial sum = 0.
*/
const arr = [1800, 123, 3598];
let sum = 0 ;

// Using the forEach() method
arr.forEach(
	function sumUntilNow(element) {
		sum = sum + element;
		console.log(sum);  
	}
);  

// Logging the answer
console.log("Sum of the elements of the arr = " + sum);

 

Output:

Output

concat() method

When we want to combine two or more arrays into one single array, we use the concat() method. It does not change the original arrays and rather returns a new array.

// Creating arrays along with elements.
const arr = ["Be", "a"]; 
const arr1 = ["Coding", "Ninja"];

// Writing the answer function
const answer = arr.concat(arr1);  

// Logging the Original and the new array
console.log("Original Arrays :");
console.log(arr, arr1) ;
console.log("New Array : ") ;
console.log(answer) ;

 

Output:

Output

join() method

We saw how we could concatenate more than one array, but what if we want to concatenate all the elements of a single array? For this, we use the join() method. The parameter which we give in the join method is used as characters between the elements while joining. 

// Creating array along with elements.
const arr = ["Be", "a", "Coding", "Ninja"];

// Writing the answer function
const answer = arr.join(" ");  

// Logging the answer
console.log(answer);

 

Output:

Output

What if we want to join without any characters or commas?

We will see this through a simple example.

// Creating array along with elements.
const arr = ["1800", "123", "3598"];

/*
	We want 18001233598 as the answer 
	This is a special number try dialing it
	Writing the answer function
*/
const answer = arr.join("");  

// Logging the answer
console.log(answer);


Output:

Output

map() method

The map() method takes the functions as parameters and creates a new array with the results of applying them to each element. 

// Creating array along with elements.
const arr = [1800, 123, 3598];

// Writing the answer function
const ans = arr.map(x => x - 100) ;

// Logging the answer
console.log(ans);

 

Output:

Output

flat() method

We use the flat() method while working with the multidimensional arrays. We use this function to flatten the depth of the array to a specific limit, which has the default value of 1. 

// Creating 3-D array along with elements.
const arr = [[1800], [123], [3598]];

// Writing the answer function
const ans = arr.flat() ;

// Logging the answer and the original array
console.log("Original Array :");
console.log(arr) ;
console.log("New Array : ") ;
console.log(ans) ;

 

Output:

Output

pop() method

We use this method to remove the last element of the array. This method returns the last element too.

// Creating array along with elements.
const arr = [1800, 123, 3598];

// Writing the answer function
const ans = arr.pop() ;

// Logging the answer and the array
console.log("Array after popping :");
console.log(arr) ;
console.log("Popped Element : ") ;
console.log(ans) ;

 

Output:

Output

push() method

We saw how we could remove an element from the end of the array. But how can we add an element there? We can achieve this using the push method. It adds elements at the end of the array.

// Creating array along with elements.
const arr = [1800, 123];

// Writing the answer function
const ans = arr.push(3598) ;

// Logging the array
console.log("Array after pushing :");
console.log(arr) ;

 

Output:

Output

filter() method

We use this method to extract only the elements which satisfy the required conditions. We are not changing the original array; it returns a new one.

// Creating array along with elements.
const arr = ["Be", "a", "Coding", "Ninja"];

// Writing the answer function
const answer = arr.filter(arr => arr.length > 4);  

// Logging the Original and the new array
console.log("Original Array :");
console.log(arr) ;
console.log("New Array : ") ;
console.log(answer) ;

 

Output:

Output

sort() method

We use this method to arrange the elements of an array in ascending (default) order. It returns the sorted array. We also can give a compare function as the parameter to this method for customizing the type of sorting. This method does sorting on the original array.

// Creating array along with elements.
const arr = ["Be", "a", "Coding", "Ninja"];

// Apply the sort function
arr.sort();  

// Logging the sorted array
console.log(arr);

 

Output:

Output

shift() method

We use this method if we want to remove the first element of the array. We update the array by using this method. The shift() method returns the element removed from the array. 

// Creating array along with elements.
const arr = ["Be", "a", "Coding", "Ninja"];

// Writing the answer function
const answer = arr.shift();  

// Logging the answer and the updated array
console.log("The shifted element = " + answer);
console.log(arr);

 

Output:

Output

unshift() method

We saw how we could remove the first element of the array. But now, if we want to add new elements to the array in the beginning, we will use the unshift() method. This method returns the length of the updated array. 

// Creating array along with elements.
const arr = ["Be", "a", "Coding", "Ninja"];

// Writing the answer function
const answer = arr.unshift("Join", "Now");  

// Logging the answer and the updated array
console.log("New length of the array = " + answer);
console.log(arr);

 

Output:

Output

slice() method

We use this method to create a new subarray from the array. We give the starting and ending positions from where we want to slice. The starting position is included, and the ending position is excluded. This method does not change the original array in any way.

// Creating array along with elements.
const arr = ["Be", "a", "Coding", "Ninja"];

// Writing the slice function
const newArray = arr.slice(1,3);  

// Logging the Original and the new array
console.log("Original Array :");
console.log(arr) ;
console.log("New Array : ") ;
console.log(newArray) ;

 

Output:

Output

 

toString() method

We use this method to convert the array into a string.

// Creating array along with elements.
const arr = [1800, 123, 3598];

// Writing the answer function
const ans = arr.toString() ;

/* 
    Logging the type of answer
    Logging the answer
*/
console.log(typeof ans);
console.log(ans);

 

Output:

Output

Frequently Asked Questions

What is an array?

An array is a single object that stores multiple values in a list. Thus, we also call them "list-objects."

Why do we need arrays?

It would have been very tough to store every element individually, especially when we have so many of them. Arrays in JavaScript help us to tackle this problem.

How to join elements of the array without any characters or commas?

To join elements without any characters or commas, we can just pass an empty character in the parameter of the join function. In this way, arr.join("").

How to start searching for an element from a specified index?

To start searching for an element in the array from a specified index, we use the indexOf method. In this method, along with the element to be searched, we can also pass the index from where we want to start the search.

What does the unshift method return? 

The unshift method returns the size(length) of the updated array. 

Conclusion

In this article, we studied the widely used methods of JavaScript arrays. We first started with defining arrays and array methods. Then read about some of the most useful array methods. Now, If you are interested in JavaScript and want to become a great web developer, check out this amazing JavaScript course on web development.

Check out our articles if you think this blog has helped you enhance your knowledge and want to learn more. Visit our website to read more such blogs. 

  1. JavaScript Full Library 
  2. Object Oriented Programming In JavaScript 
  3. Objects in JS 
  4. Getters and Setters in Js 
  5. Constructor, operator "new" 


Recommended problems : 


For placement preparations, you must look at the problemsinterview experiences, and interview bundles. Enroll in our courses and refer to the mock tests and problems available; look at the Problem Sheets interview experiences, and interview bundle for placement preparations. You can also book an interview session with us.  

Consider our paid courses, however, to give your career a competitive advantage!

Happy Coding!

Previous article
Array in Javascript
Next article
JavaScript typed arrays
Live masterclass