JAVASCRIPT ARRAY METHODS


In this article, you are going to learn all the array methods in javascript in detail with various examples. You will learn how to use them in your code.

Array Methods In Javascript

Array methods are built-in functions in javascript which has a special task to be performed on an array. forEach, sort, map, split, etc are the most useful array methods.

These array methods either change the original array or return a new array by modifying it.

Here is a simple example of an array and forEach array method to loop through an array.

Test array:

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

Using forEach() method to loop through the array and print elements.

arr.forEach(function(element){
  console.log(element);
});

Array Length

Before we jump to array methods let's take a look at a very important array property which is the length property.

The length property in javascript when applied on the array it returns the number of elements in the array. It is very frequently used when working with arrays.

Either you want to loop through the array or you want to know the number of elements in the array you can use the length property to get the number of elements in the array.

Example

const arr = [1, 2, 3, 4, 5];
// length property
console.log("Length of array = " + arr.length);
Try It

Javascript Array Methods List

Here is a list of javascript array methods. We will go in detail with each method further in the section.

Click on any method to jump to the section.

  1. concat()
  2. copyWithIn()
  3. entries()
  4. every()
  5. fill()
  6. filter()
  7. find()
  8. findIndex()
  9. forEach()
  10. Array.from()
  11. includes()
  12. indexOf()
  13. isArray()
  14. join()
  15. lastIndexOf()
  16. map()
  17. push()
  18. pop()
  19. shift()
  20. unshift()
  21. reduce()
  22. reverse()
  23. slice()
  24. some()
  25. sort()
  26. splice()
  27. toString()
  28. values()

Now let's look at each String method in detail.


1. Javascript concat Array

The concat() array method in javascript is used to merge 2 or more arrays or values into a single array.

The concat() method does not change the original array but returns a new array by merging them.

Syntax:

var newArray = arr.concat(arg1, arg2, ...)

Here the arguments of the method can be an array and/or any other data type.

Example

const numbers = [1, 2, 3];
const characters = ['a', 'b', 'c'];
const booleans = [true, false];

// single argument
console.log(numbers.concat(characters));
// multiple argument
console.log(numbers.concat(characters, booleans));
// passing values
console.log(numbers.concat(characters, 24, "John", {x: 12, y: 13}));
Try It

Alternate method:

Apart from concat() method, you can also spread operator (...) to merge multiple arrays and values into a single array.

Here is the above example using the spread operator.

Example

const numbers = [1, 2, 3];
const characters = ['a', 'b', 'c'];
const booleans = [true, false];

console.log([...numbers, ...characters]);
// multiple argument
console.log([...numbers, ...characters, ...booleans]);
// passing values
console.log([...numbers, 24, "John"]);

2. copyWithIn Method

The copyWithIn() method in javascript copies a part of the same array within the same calling array.

This method modifies elements of the original array but the length of the array is not modified.

Syntax:

arr.copyWithIn(targetIndex);
arr.copyWithIn(targetIndex, startIndex);
arr.copyWithIn(targetIndex, startIndex, endIndex);

The copyWithIn() method takes three arguments:

Example

//since array is modified we took 3 array with same elements
const arr1 = ['a', 'b', 'c', 'd', 'e', 1, 2, 3];
const arr2 = ['a', 'b', 'c', 'd', 'e', 1, 2, 3];
const arr3 = ['a', 'b', 'c', 'd', 'e', 1, 2, 3];

// copy elements from index 0 to last index to index 2
console.log(arr1.copyWithin(2));
// copy elements from index 4 to last index to index 2
console.log(arr2.copyWithin(2, 4));
// copy elements from index 4 to index 6 to index 2
console.log(arr3.copyWithin(2, 4, 6));
Try It

When you use the negative index, the method starts counting from the end of the array. i.e -1 is the last index, -2 is the second last index, and so on.

Here is an example of using a negative index.

Example

const arr1 = ['a', 'b', 'c', 'd', 'e', 1, 2, 3];
const arr2 = ['a', 'b', 'c', 'd', 'e', 1, 2, 3];

console.log(arr1.copyWithin(2, -3));
console.log(arr2.copyWithin(-5, -3, -1));

3. entries Method In Javascript

The entries() method in javascript returns a new Array Iterator object that contains the key/value pairs for each index in the array.

The entries() method does not change the original array but returns a new array iterator object.

This iterator can be used to get the next element in the array by calling the next() method on the iterator object.

Syntax:

arr.entries()

Here the entries() method does not take any argument.

Example

const arr = ["a", "b", "c", "d", "e"];
const iterator1 = arr.entries();
console.log(iterator1.next());
console.log(iterator1.next().value);
console.log(iterator1.next().value);

// using for...of loop
const iterator2 = arr.entries();
for (const [index, value] of iterator2) {
  console.log(index, value)
}
Try It

4. every() Method

The every() method in javascript executes a function for each element in the array and returns true if the function returns true for all elements.

The original array is not modified by this method.

Syntax:

arr.every(callback(currentValue, index, arr), thisArg)

You can define the callback function within the method or you can define it outside the method.

The callback function takes three arguments:

Let's see an example where we are checking if all the elements in the array are even.

Example

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [22, 42, 86, 100, 4];

function isEven(num) {
  return num % 2 === 0;
}

console.log(arr1.every(isEven));
console.log(arr2.every(isEven));

5. fill Method In Javascript

The fill() method in javascript returns a modified array by filling a specified index with the specified value.

The original array is not modified by the fill() method.

Syntax:

arr.fill(value);
arr.fill(value, start);
arr.fill(value, start, end);

The fill() method accepts 3 arguments:

Example

const arr = ["a", "a", "a", "a", "a", "a", "a"];

// fill the whole array with "b"
console.log(arr.fill("b"));

// fill the array from index 2 to last with "c"
console.log(arr.fill("c", 2));

// fill the array from index 4 to index 6 with "d"
console.log(arr.fill("d", 4, 6));
Try It

This method can be used when you create an array of a specified size and you want to fill the array with a particular value.

Example

const arr = new Array(10).fill("a");
console.log(arr);

6. filter Method In Javascript

The filter() method in javascript is used to create a new array with the elements of the same array if elements pass a certain condition.

The filter() methods accept a callback function as an argument.

The callback function returns true or false after checking some conditions over each and every element. If true is returned then that element is added to the new array, else discarded.

Finally, a new array is returned with those added elements.

Syntax:

arr.filter(callback(currentValue, index, arr), thisArg)

The argument currentValue is necessary and index and arr are optional.

Example

const arr = [10, 12, 5, 15, 2, 32, 20, -5, 23];

// create a new array with all the elements greater than 10
console.log(arr.filter((element) => element > 10));

// array with only even numbers
console.log(arr.filter((element) => element % 2 === 0));
Try It

7. find Method In Javascript

The find() method in javascript is returned the first value of the array elements which satisfies the provided condition.

The find() method accepts a callback function where you can define the condition.

The callback function returns true or false after checking some conditions over each and every element. If true is returned then the element is returned, else the next element is checked.

Finally, the first element which satisfies the condition is returned.

Syntax:

arr.find(callback(currentValue, index, arr), thisArg)

Let's see an example where we are finding the first element which is greater than 10.

Example

const arr = [1, 10, 2, 25, 5, 15];

// method return the first element which is greater than 10
console.log(arr.find((element) => element > 10));
Try It

If nothing is found then undefined is returned.

The find() method does not return the index of the element which satisfies the condition to get index use findIndex() method.


8. findIndex Method In Javascript

The findIndex() method is the same as find() but it returns the index value of the element, not the value itself.

If no such element exists then returns -1.

The findIndex() method accepts a callback function where you can define the condition.

Syntax:

arr.findIndex(callback(currentValue, index, arr), thisArg)

Let's find the index of first element which is greater than 10.

Example

const arr = [1, 10, 2, 25, 5, 15];

// method return the index of first element which is greater than 10
console.log(arr.findIndex((element) => element > 10));
Try It

9. forEach Method In Javascript

The forEach() method in javascript is used to iterate over each and every element of the array and execute a function for all elements.

It accepts a callback function as an argument.

Syntax:

arr.forEach(callback(currentValue, index, arr), thisArg)

The callback function accepts three arguments:

In the below example we are looping through the array and printing the elements.

Example

const arr = [10, 12, 37, 24, 65];

function print(element, index) {
  console.log(element + " is at index " + index);
}

// using forEach method
arr.forEach(print);
Try It

# Printing sum of the square of all elements of the array

Example

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

var sum = 0;
function square(element) {
  sum += element * element;
}

arr.forEach(square);
console.log("sum = " + sum);

10. Array.from Method In Javascript

The Array.from() method in javascript is used to convert an array like object to an array.

What do we mean by an array like object?

An array like object is an object which has a length property. Example: string, arguments, NodeList, HTMLCollection, etc.

To convert these objects to a proper array pass the object as an argument to the Array.from() method.

Syntax:

Array.from(arrayLike)

The Array.from() method returns a new array and does not change the original array.

Example

const alphabets = "abcdefghijklmnopqrstuvwxyz";

// converting string to array
const arr = Array.from(alphabets);
console.log(arr);

const obj = {
  0: "a",
  1: "b",
  2: "c",
  length: 3
};
// converting object to array
const arr2 = Array.from(obj);
console.log(arr2);

11. includes Method In Javascript

The includes() method in javascript determines whether certain values exist in the array or not. If the value exists in the array then the method returns true else return false.

Syntax:

arr.includes(searchElement, fromIndex)

The function accepts 2 arguments:

Example

const fruit = ["mango", "banana", "apple", "orange", "watermelon"]
console.log(fruit.includes("apple")); // true

const alphabets = ["a", "b", "c", "d", "e"];
console.log(alphabets.includes("a")); // true
console.log(alphabets.includes("a", 1)); // false
Try It

12. indexOf Method In Javascript

The indexOf() method in javascript returns the first index of the element passed as an argument. If the value does not exist then returns -1.

Syntax:

arr.indexOf(searchElement, fromIndex)

The function accepts 2 arguments:

Example

const arr = ["a", "b", "c", "d", "e"];

// get the index of "c"
console.log(arr.indexOf("c"));
Try It

What is difference between indexOf() and findIndex()?

The indexOf() method accepts a direct value as an argument whereas the findIndex() method accepts a callback function as an argument and gives more flexibility to the user.


13. isArray Method In Javascript

The isArray() method in javascript returns true if the passed argument is an array else returns false.

It is used to check whether the passed argument is an array or not.

Syntax:

Array.isArray(arr)

Example

const arr = ["a", "b", "c", "d", "e"];

// check if array
console.log(Array.isArray(arr));

console.log(Array.isArray("abc")); // false

14. join Method In Javascript

The join() method in javascript joins all elements of the array as a string separated by commas or by some specified separator and returns it as a string.

The function accepts 1 argument which is a separator. It is optional and its default value is a comma (",").

Syntax:

arr.join(separator)

This method is used to join the elements of the array as a string.

Example

const fruit = ["mango", "banana", "apple", "orange", "watermelon"];

// default separator (,)
console.log(fruit.join());
// blank separator
console.log(fruit.join(''));
// custom separator
console.log(fruit.join('-'));
Try It

15. lastIndexOf Method In Javascript

The lastIndexOf() method returns the last index of the element passed as an argument in the method. If the value does not exist then returns -1.

Syntax:

arr.lastIndexOf(searchElement, fromIndex)

The method accepts 2 arguments:

Example

const arr = ["b", "d", "i", "b", "d", "f", "i", "b", "d", "g", "i"];

// get the index of 'd'
console.log(arr.lastIndexOf('d'));
// get the index of 'g'
console.log(arr.lastIndexOf('g'));

16. map Method In Javascript

The map() method in javascript is one of the most useful array method, it returns a new array by filling the array with the results of the callback function running for each element of the array.

You have to pass a callback function as an argument to the map() method. The callback function is called for each element of the array and the return value of the callback function is stored in the new array.

Syntax:

arr.map(callback(currentValue, index, array), thisArg)

The callback function in the map method accepts 3 arguments:

Example

const num = [1, 2, 3, 4, 5];

// multiply each element by its index
const newArray = num.map((element, index) => element * index);
console.log(newArray);
Try It

17. push Method In Javascript

The push() method in javascript is used to add one or more elements to the end of the calling array.

After adding the elements to the array, the method returns the new length of the array.

Syntax:

arr.push(value1, value2, ...)

This method accepts 1 or more arguments.

Example

const fruit = ["mango", "banana"];

// add elements to the end of the array
fruit.push("apple");
console.log(fruit);
// add 2 new elements to the end
fruit.push("orange", "watermelon");
console.log(fruit);
Try It

18. pop Method In Javascript

The pop() method in javascript removes the last element from the array and returns the removed elements.

If the array is empty, the method returns undefined.

Syntax:

arr.pop()

Here is an example of the pop() method:

Example

const fruit = ["mango", "banana", "apple", "orange", "watermelon"];
fruit.pop();
console.log("After 1 pop => " + fruit);
fruit.pop();
console.log("After 2 pop => " + fruit);
Try It

19. shift Method In Javascript

Just like the pop() method shift() method also removes the element from the array but instead of removing the last element, it removes the first element.

If the array is empty, the method returns undefined.

Syntax:

arr.shift()

Here is an example of the shift() method:

Example

const fruit = ["mango", "banana", "apple", "orange", "watermelon"];
fruit.shift();
console.log("After 1 shift => " + fruit);
fruit.shift();
console.log("After 2 shift => " + fruit);
Try It

20. unshift Method In Javascript

Like push() method unshift() method also adds the element to the array but instead of adding it to the ending of the array, it adds it to the beginning.

This method returns the new length of the array.

Syntax:

arr.unshift(value1, value2, ...)

This method accepts 1 or more arguments.

Example

const fruit = ["orange", "watermelon"];

// add elements to the beginning of the array
fruit.unshift("apple");
console.log("After 1st unshift => " + fruit);
// add 2 new elements to the beginning
fruit.shift("mango", "banana");
console.log("After 2nd unshift => " + fruit);
Try It

21. reduce Method In Javascript

The reduce() method in javascript reduce the array element to a single value, using a reducer function.

It is a little bit tricky to understand the reduce() method. Let's see how it works.

Syntax:

arr.reduce(callback(accumulator, currentValue, currentIndex, array))

The reducer callback function accepts the following arguments:

The callback function seems to be executed for each element but it starts execution from the second element. The first element is the initial value.

At the start, the accumulator becomes the value at index 0 and the current value is the value at index 1.

In the second iteration, the accumulator becomes the value returned by the callback function in the previous iteration and the current value is the value at index 2.

Example

const num = [1, 2, 3, 4, 5];

// sum of all elements
const sum = num.reduce((acc, curr) => acc + curr);
console.log(sum);
Try It

Here is another example to find the biggest number in the array:

Example

const num = [24, 53, 78, 91, 12];

// find biggest number
const max = num.reduce((acc, curr) => Math.max(acc, curr));
console.log(max);

22. reverse Method In Javascript

The reverse() method in javascript reverse the array elements from first to last.

const num = [1, 2, 3, 4, 5];
console.log(num.reverse());
Try It

23. slice Method In Javascript

The slice() method in javascript returns a new array by copying the calling array's elements in new the array.

The slice() method accepts 2 arguments:

const num1 = [1, 2, 3, 4, 5];
const num2 = num1.slice();
const num3 = num1.slice(2);
const num4 = num1.slice(2,4);
console.log(num2);
console.log(num3);
console.log(num4);
Try It

24. some Method In Javascript

The some() method in javascript determines whether at least one element in the array passes certain conditions by providing a callback function.

If any of array element passes the test then it returns true, else returns false.

The callback function's first argument is the current element and the second element is the index of the element which is also optional.

const num = [1, 2, 3, 4, 5];
console.log(num.some((element) => element > 3));
Try It

25. sort Method In Javascript

The sort() method in javascript sort the array element in ascending order according to the character's Unicode value. Means it convert its element to string and sort it by comparing the string in UTF-16 code.

The sort() function accepts a compare function which defines some sorting order. This compare function has 2 arguments, 'firstElement': the first element for comparison and 'secondElement': these second element for comparison.

const fruit = ["mango", "banana", "apple", "orange", "watermelon"];
console.log(fruit.sort());
const num = [2, 321, 100, 1310, 43];
console.log(num.sort());
console.log(num.sort((firstElement, secondElement)=>{
  return firstElement - secondElement;
}));
Try It

26. splice Method In Javascript

The splice() method in javascript changes the array element by replacing or removing the array element from the array. It can also add elements to the desired index in the array either by keeping or removing the rest elements of the array.

arr.splice(index, deleteCount, replaceBy)
const day = ["monday", "wednesday", "friday", "sunday"];
day.splice(1, 0, "tuesday");
console.log(day);
day.splice(4, 1, "saturday");
console.log(day);
day.splice(3, 2);
console.log(day);
Try It

27. toString Method In Javascript

The toString() method in javascript returns a string representing the elements of the array.

const arr = [1, "star", 34, true, 23];
console.log(arr.toString());
Try It

28. values Method In Javascript

The values() method in javascript returns a new array iterator that contains values of each index in the array.

const array1 = [1, "star", 34, true, 23];
const iterator = array1.values();
for (const value of iterator) {
  console.log(value);
}
Try It

Conclusion

In this tutorial, we have learned how to create an array in javascript, how to access array elements, how to add, remove, replace array elements, how to sort array elements, how to use some method in javascript, how to use the splice method in javascript, how to use toString method in javascript, how to use values method in javascript.