Learn everything about JavaScript Array Methods with code examples. This guide is the ultimate cheat sheet of Javascript Array methods.

JavaScript Array Methods Complete Guide
JavaScript Array Methods Complete Guide

Arrays are one of the most commonly used data structures in JavaScript. They allow us to store and manipulate collections of data in a flexible and efficient way.

To work with arrays effectively, it’s important to be familiar with the built-in array methods provided by JavaScript.

In this article, we’ll go through some of the most commonly used array methods and provide code examples for each one.

By the end of this article, you’ll have a solid understanding of how to use these methods to manipulate and work with arrays in your JavaScript programs.

1. concat()

The concat() method is used to combine two or more arrays into a single array. It doesn’t modify the existing arrays, instead, it returns a new array.


   const array1 = [1, 2, 3];
   const array2 = [4, 5, 6];
   const newArray = array1.concat(array2);
   console.log(newArray); // [1, 2, 3, 4, 5, 6]

2. push()

The push() method adds one or more elements to the end of an array and returns the new length of the array.

   const array = [1, 2, 3];
   const length = array.push(4, 5);
   console.log(array); // [1, 2, 3, 4, 5]
   console.log(length); // 5

3. pop()

The pop() method removes the last element from an array and returns that element.

   const array = [1, 2, 3];
   const lastElement = array.pop();
   console.log(array); // [1, 2]
   console.log(lastElement); // 3

4. shift()

The shift() method removes the first element from an array and returns that element. The remaining elements in the array are shifted down to occupy the empty index.

   const array = [1, 2, 3];
   const firstElement = array.shift();
   console.log(array); // [2, 3]
   console.log(firstElement); // 1

5. unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

const array = [1, 2, 3];
const length = array.unshift(0, -1);
console.log(array); // [0, -1, 1, 2, 3]
console.log(length); // 5

6. slice()

The slice() method returns a shallow copy of a portion of an array into a new array object.

const array = [1, 2, 3, 4, 5];
const newArray = array.slice(1, 4);
console.log(newArray); // [2, 3, 4]

7. splice()

The splice() method changes the content of an array by removing or replacing existing elements and/or adding new elements in place.

const array = [1, 2, 3, 4, 5];
const removedElements = array.splice(2, 2, 6, 7);
console.log(array); // [1, 2, 6, 7, 5]
console.log(removedElements); // [3, 4]

8. forEach()

The forEach() method executes a provided function once for each array element.

const array = [1, 2, 3];
array.forEach((element) => {
  console.log(element);
});
// Output:
// 1
// 2
// 3

9. map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

const array = [1, 2, 3];
const newArray = array.map((element) => {
  return element * 2;
});
console.log

10. reduce()

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. The reducer function takes in two arguments: an accumulator and the current value being processed. The accumulator is initialized to an initial value that you provide.

See also  Difference Between Cookies and Sessions

Here’s an example of using reduce() to find the sum of all the elements in an array:

const array = [1, 2, 3, 4, 5];
const sum = array.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);
console.log(sum); // 15

11. filter()

The filter() method creates a new array with all the elements that pass a test (that you provide) implemented by the callback function. The callback function takes in one argument (the current value being processed), and returns true or false depending on whether the element passes the test.

Here’s an example of using filter() to create a new array containing only the even numbers from an original array:

const array = [1, 2, 3, 4, 5];
const evenNumbers = array.filter((element) => {
  return element % 2 === 0;
});
console.log(evenNumbers); // [2, 4]

12. sort()

The sort() method is used to sort the elements of an array in place and returns the sorted array. By default, the sort order is based on each element’s string representation. However, you can provide a function that defines the sort order.

Here’s an example of using sort() to sort an array of numbers in ascending order:

const array = [3, 1, 4, 2, 5];
array.sort((a, b) => {
  return a - b;
});
console.log(array); // [1, 2, 3, 4, 5]

13. find()

The find() method returns the value of the first element in an array that satisfies a provided testing function. The testing function is called on each element of the array until it returns true. Once a match is found, the find() method immediately returns the value of that element.

Here’s an example of using find() to find the first even number in an array:

const array = [1, 3, 4, 5, 7, 8];
const evenNumber = array.find((element) => {
  return element % 2 === 0;
});
console.log(evenNumber); // 4

14. findIndex()

The findIndex() method returns the index of the first element in an array that satisfies a provided testing function. The testing function is called on each element of the array until it returns true. Once a match is found, the findIndex() method immediately returns the index of that element.

Here’s an example of using findIndex() to find the index of the first even number in an array:

const array = [1, 3, 4, 5, 7, 8];
const evenNumberIndex = array.findIndex((element) => {
  return element % 2 === 0;
});
console.log(evenNumberIndex); // 2

15. flat()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. By default, the depth is 1, so it only flattens one level of nested arrays.

Here’s an example of using flat() to flatten a nested array:

const nestedArray = [1, 2, [3, 4], [5, [6]]];
const flattenedArray = nestedArray.flat();
console.log(flattenedArray); // [1, 2, 3, 4, 5, [6]]

16. includes()

The includes() method determines whether an array includes a certain value among its elements, returning true or false as appropriate.

Here’s an example of using includes() to check if an array contains a specific value:

const array = [1, 2, 3, 4, 5];
const containsThree = array.includes(3);
console.log(containsThree); // true

18. flatMap()

The flatMap() method maps each element of an array to a new array and then flattens the result into a single array. The mapping function can also be used to transform each element before flattening.

See also  Static Testing Complete Tutorial

Here’s an example of using flatMap() to create a new array by mapping each element to an array of squares and then flattening the result:

const array = [1, 2, 3, 4, 5];
const squares = array.flatMap((element) => {
  return [element ** 2];
});
console.log(squares); // [1, 4, 9, 16, 25]

19. group()

The group() method groups the elements of an array based on a specified key function. It returns a new object where each key is a unique value returned by the key function, and the corresponding value is an array of all elements that share that key.

Here’s an example of using group() to group an array of people by their age:

const array = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 25 },
  { name: "Dave", age: 35 },
];
const result = array.reduce((acc, curr) => {
  const key = curr.age;
  if (!acc[key]) {
    acc[key] = [];
  }
  acc[key].push(curr);
  return acc;
}, {});
console.log(result);
// {
//   "25": [{ "name": "Alice", "age": 25 }, { "name": "Charlie", "age": 25 }],
//   "30": [{ "name": "Bob", "age": 30 }],
//   "35": [{ "name": "Dave", "age": 35 }]
// }

20. join()

The join() method joins all elements of an array into a string and returns the string. It takes an optional separator parameter, which specifies the string to use as the separator between the array elements. If no separator is provided, the default separator is a comma.

Here’s an example of using join() to concatenate the elements of an array into a string with a custom separator:

const array = ["apple", "banana", "orange"];
const separator = " | ";
const result = array.join(separator);
console.log(result); // "apple | banana | orange"

22. keys()

The keys() method returns an array iterator object with the keys of an array. It can be used to loop through the indices of an array.

Here’s an example of using keys() to loop through the indices of an array:

const array = ["apple", "banana", "orange"];
const keysIterator = array.keys();
for (const key of keysIterator) {
  console.log(key); // 0, 1, 2
}

23. reduce()

The reduce() method applies a function to each element of an array and accumulates the result into a single value. It takes two parameters: a callback function and an optional initial value. The callback function takes four parameters: an accumulator, a current value, the current index, and the array itself.

Here’s an example of using reduce() to calculate the sum of the elements of an array

const array = [1, 2, 3, 4];
const sum = array.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10

24. reverse()

The reverse() method reverses the order of the elements of an array in place and returns the reversed array.

Here’s an example of using reverse() to reverse the order of the elements of an array:

const array = ["apple", "banana", "orange"];
array.reverse();
console.log(array); // ["orange", "banana", "apple"]

25. toString()

The toString() method returns a string representation of an array. It concatenates the elements of the array into a string with a comma separator.

See also  JavaScript Object Methods With Examples

Here’s an example of using toString() to convert an array to a comma-separated string:

const array = ["apple", "banana", "orange"];
const str = array.toString();
console.log(str); // "apple,banana,orange"

26. values()

The values() method returns an array iterator object with the values of an array. It can be used to loop through the values of an array.

Here’s an example of using values() to loop through the values of an array:

const array = ["apple", "banana", "orange"];
const valuesIterator = array.values();
for (const value of valuesIterator) {
  console.log(value); // "apple", "banana", "orange"
}

27. every()

The every() method tests whether all elements in an array pass a certain condition. It takes a callback function that takes three parameters: the current element, the index of the element, and the array itself. It returns a boolean value indicating whether all elements pass the condition.

Here’s an example of using every() to check if all elements of an array are positive:

const array = [1, 2, 3, 4];
const allPositive = array.every((element) => element > 0);
console.log(allPositive); // true

28. findLastIndex()

The findLastIndex() method returns the index of the last element in an array that satisfies a certain condition. It takes a callback function that takes three parameters: the current element, the index of the element, and the array itself. It returns the index of the last element that satisfies the condition or -1 if no element satisfies the condition.

Here’s an example of using findLastIndex() to find the index of the last negative element in an array:

const array = [1, -2, 3, -4];
const lastIndex = array.findLastIndex((element) => element < 0);
console.log(lastIndex); // 3

29. fill()

The fill() method fills all the elements of an array with a static value. It takes the value to fill and two optional parameters: the start index and the end index (exclusive) of the range to fill. It modifies the original array.

Here’s an example of using fill() to fill an array with a static value:

const array = [1, 2, 3, 4];
array.fill(0);
console.log(array); // [0, 0, 0, 0]

30. of()

The of() method creates a new array with a variable number of arguments. It takes any number of arguments and returns an array with those arguments as elements.

Here’s an example of using of() to create a new array with a variable number of elements:

const array = Array.of(1, 2, 3, 4);
console.log(array); // [1, 2, 3, 4]

31. at()

The at() method returns the element at a certain index in an array. It takes the index of the element to return and returns the element or undefined if the index is out of range.

Here’s an example of using at() to access the element at a certain index in an array:

const array = [1, 2, 3, 4];
const element = array.at(2);
console.log(element); // 3