DEV Community

Cover image for 30 Essential Array Methods in JavaScript with Examples
Mahabubur Rahman
Mahabubur Rahman

Posted on

30 Essential Array Methods in JavaScript with Examples

Arrays are a fundamental data structure in JavaScript, used to store multiple values in a single variable. JavaScript provides various built-in methods to manipulate and interact with arrays. Here are ten important array methods every JavaScript developer should know, complete with examples and explanations.

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

  • Example:
let fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits); // Output: ['apple', 'banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

Explanation: Here, push('orange') adds 'orange' to the end of the fruits array.

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

  • Example:
let fruits = ['apple', 'banana', 'orange'];
let lastFruit = fruits.pop();
console.log(lastFruit); // Output: 'orange'
console.log(fruits); // Output: ['apple', 'banana']
Enter fullscreen mode Exit fullscreen mode

Explanation: pop() removes 'orange' from the end of the array and returns it.

3. shift()
The shift() method removes the first element from an array and returns that element.

  • Example:
let fruits = ['apple', 'banana', 'orange'];
let firstFruit = fruits.shift();
console.log(firstFruit); // Output: 'apple'
console.log(fruits); // Output: ['banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

Explanation: shift() removes 'apple' from the beginning of the array and returns it.

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

  • Example:
let fruits = ['banana', 'orange'];
fruits.unshift('apple');
console.log(fruits); // Output: ['apple', 'banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

Explanation: unshift('apple') adds 'apple' to the beginning of the fruits array.

5. splice()
The splice() method changes the contents of an array by removing, replacing, or adding elements at a specific index.

  • Example:
let fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1, 'grape'); // Removes 1 element at index 1 and adds 'grape'
console.log(fruits); // Output: ['apple', 'grape', 'orange']
Enter fullscreen mode Exit fullscreen mode

Explanation: splice(1, 1, 'grape') removes 1 element at index 1 ('banana') and adds 'grape' at that position.

6. slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).

  • Example:
let fruits = ['apple', 'banana', 'orange', 'grape'];
let citrus = fruits.slice(1, 3);
console.log(citrus); // Output: ['banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

Explanation: slice(1, 3) creates a new array containing elements from index 1 to index 2 (excluding index 3).

7. concat()
The concat() method is used to merge two or more arrays. This method does not change the existing arrays but returns a new array.

  • Example:
let fruits = ['apple', 'banana'];
let moreFruits = ['orange', 'grape'];
let allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Output: ['apple', 'banana', 'orange', 'grape']
Enter fullscreen mode Exit fullscreen mode

Explanation: concat(moreFruits) merges the fruits and moreFruits arrays into a new array.

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

  • Example:
let fruits = ['apple', 'banana', 'orange'];
fruits.forEach(function(fruit) {
  console.log(fruit);
});
// Output: 
// 'apple'
// 'banana'
// 'orange'
Enter fullscreen mode Exit fullscreen mode

Explanation: forEach() iterates through each element in the fruits array and logs it to the console.

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

  • Example:
let numbers = [1, 2, 3];
let doubled = numbers.map(function(number) {
  return number * 2;
});
console.log(doubled); // Output: [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Explanation: map() applies the provided function to each element in numbers and creates a new array with the results.

10. filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.

  • Example:
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(function(number) {
  return number % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]
Enter fullscreen mode Exit fullscreen mode

Explanation: filter() applies the provided function to each element in numbers and returns a new array with the elements that pass the test.

11. reduce()
The reduce() method executes a reducer function on each element of the array, resulting in a single output value.

  • Example:
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 10
Enter fullscreen mode Exit fullscreen mode

Explanation: reduce() sums up all elements in the numbers array, starting with an initial value of 0.

12. find()
The find() method returns the value of the first element in the array that satisfies the provided testing function.

  • Example:
let numbers = [1, 2, 3, 4];
let found = numbers.find(function(number) {
  return number > 2;
});
console.log(found); // Output: 3
Enter fullscreen mode Exit fullscreen mode

Explanation: find() returns the first element in the numbers array that is greater than 2.

13. findIndex()
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.

  • Example:
let numbers = [1, 2, 3, 4];
let index = numbers.findIndex(function(number) {
  return number > 2;
});
console.log(index); // Output: 2
Enter fullscreen mode Exit fullscreen mode

Explanation: findIndex() returns the index of the first element in the numbers array that is greater than 2.

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

  • Example:
let fruits = ['apple', 'banana', 'orange'];
let hasBanana = fruits.includes('banana');
console.log(hasBanana); // Output: true
Enter fullscreen mode Exit fullscreen mode

Explanation: includes('banana') checks if 'banana' is in the fruits array and returns true.

15. some()
The some() method tests whether at least one element in the array passes the test implemented by the provided function.

  • Example:
let numbers = [1, 2, 3, 4];
let hasEven = numbers.some(function(number) {
  return number % 2 === 0;
});
console.log(hasEven); // Output: true
Enter fullscreen mode Exit fullscreen mode

Explanation: some() checks if there is at least one even number in the numbers array and returns true.

16. every()
The every() method tests whether all elements in the array pass the test implemented by the provided function.

  • Example:
let numbers = [2, 4, 6, 8];
let allEven = numbers.every(function(number) {
  return number % 2 === 0;
});
console.log(allEven); // Output: true
Enter fullscreen mode Exit fullscreen mode

Explanation: every() checks if all elements in the numbers array are even and returns true.

17. sort()
The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is according to string Unicode code points.

  • Example:
let fruits = ['banana', 'orange', 'apple'];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

Explanation: sort() arranges the elements of the fruits array in alphabetical order.

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

  • Example:
let fruits = ['banana', 'orange', 'apple'];
fruits.reverse();
console.log(fruits); // Output: ['apple', 'orange', 'banana']
Enter fullscreen mode Exit fullscreen mode

Explanation: reverse() reverses the order of the elements in the fruits array.

19. join()
The join() method joins all elements of an array into a string and returns this string.

  • Example:
let fruits = ['apple', 'banana', 'orange'];
let fruitString = fruits.join(', ');
console.log(fruitString); // Output: 'apple, banana, orange'
Enter fullscreen mode Exit fullscreen mode

Explanation: join(', ') concatenates all elements in the fruits array into a single string, separated by a comma and a space.

20. from()
The Array.from() method creates a new, shallow-copied array instance from an array-like or iterable object.

  • Example:
let str = 'hello';
let charArray = Array.from(str);
console.log(charArray); // Output: ['h', 'e', 'l', 'l', 'o']
Enter fullscreen mode Exit fullscreen mode

Explanation: Array.from(str) creates a new array from the string str, with each character of the string becoming an element in the array.

21. flat()
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

  • Example:
let nestedArray = [1, [2, [3, [4]]]];
let flatArray = nestedArray.flat(2);
console.log(flatArray); // Output: [1, 2, 3, [4]]
Enter fullscreen mode Exit fullscreen mode

Explanation: flat(2) flattens the nestedArray up to 2 levels deep.

22. flatMap()
The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1.

  • Example:
let numbers = [1, 2, 3];
let mappedFlatArray = numbers.flatMap(num => [num, num * 2]);
console.log(mappedFlatArray); // Output: [1, 2, 2, 4, 3, 6]
Enter fullscreen mode Exit fullscreen mode

Explanation: flatMap() applies the function to each element and flattens the result.

23. fill()
The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array length). It returns the modified array.

  • Example:
let array = [1, 2, 3, 4, 5];
array.fill(0, 2, 4);
console.log(array); // Output: [1, 2, 0, 0, 5]
Enter fullscreen mode Exit fullscreen mode

Explanation: fill(0, 2, 4) replaces elements from index 2 to 3 with 0.

24. copyWithin()
The copyWithin() method shallow copies part of an array to another location in the same array and returns it, without modifying its length.

  • Example:
let array = [1, 2, 3, 4, 5];
array.copyWithin(0, 3, 4);
console.log(array); // Output: [4, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Explanation: copyWithin(0, 3, 4) copies the element at index 3 to index 0.

25. keys()
The keys() method returns a new Array Iterator object that contains the keys for each index in the array.

  • Example:
let fruits = ['apple', 'banana', 'orange'];
let keys = fruits.keys();
for (let key of keys) {
  console.log(key);
}
// Output:
// 0
// 1
// 2
Enter fullscreen mode Exit fullscreen mode

Explanation: keys() provides an iterator over the keys (indices) of the fruits array.

26. values()
The values() method returns a new Array Iterator object that contains the values for each index in the array.

  • Example:
let fruits = ['apple', 'banana', 'orange'];
let values = fruits.values();
for (let value of values) {
  console.log(value);
}
// Output:
// 'apple'
// 'banana'
// 'orange'
Enter fullscreen mode Exit fullscreen mode

Explanation: values() provides an iterator over the values of the fruits array.

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

  • Example:
let fruits = ['apple', 'banana', 'orange'];
let entries = fruits.entries();
for (let [index, value] of entries) {
  console.log(index, value);
}
// Output:
// 0 'apple'
// 1 'banana'
// 2 'orange'
Enter fullscreen mode Exit fullscreen mode

Explanation: entries() provides an iterator over the key/value pairs of the fruits array.

28. reduceRight()
The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

  • Example:
let numbers = [1, 2, 3, 4];
let product = numbers.reduceRight(function(accumulator, currentValue) {
  return accumulator * currentValue;
}, 1);
console.log(product); // Output: 24
Enter fullscreen mode Exit fullscreen mode

Explanation: reduceRight() multiplies all elements of the numbers array from right to left.

29. toLocaleString()
The toLocaleString() method returns a string representing the elements of the array. The elements are converted to strings using their toLocaleString() methods and are separated by a locale-specific string (such as a comma ",").

  • Example:
let prices = [1234.56, 7890.12];
let localeString = prices.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
console.log(localeString); // Output: '$1,234.56,$7,890.12' 
Enter fullscreen mode Exit fullscreen mode

Explanation: toLocaleString() formats each number in the prices array according to locale-specific conventions.

30. toString()
The toString() method returns a string representing the specified array and its elements.

  • Example:
let fruits = ['apple', 'banana', 'orange'];
let stringRepresentation = fruits.toString();
console.log(stringRepresentation); // Output: 'apple,banana,orange'
Enter fullscreen mode Exit fullscreen mode

Explanation: toString() converts the fruits array into a comma-separated string.

Top comments (0)