JavaScript Array Methods: A Comprehensive Guide

who_tf_cares

Kavei Sahai

Posted on September 15, 2024

JavaScript Array Methods: A Comprehensive Guide

Arrays are one of the most fundamental data structures in JavaScript. With an array, you can store multiple values in a single variable. JavaScript provides numerous built-in methods to manipulate arrays, making them incredibly versatile. In this post, we'll explore all the built-in array methods and how to use them effectively in your JavaScript projects.

Core Methods

forEach()

The forEach() method allows you to iterate over an array and execute a provided function once for each element in the array. It's a simple way to loop through an array.

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

array.forEach((element) => {
  console.log(element);
});
Enter fullscreen mode Exit fullscreen mode

map()

The map() method creates a new array populated with the results of calling a provided function on every element in the array. It's typically used for transforming data.

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

const doubled = array.map((element) => element * 2);

console.log(doubled); // [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function. It's useful when you need to filter out certain elements from an array based on a condition.

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

const evenNumbers = array.filter((element) => element % 2 === 0);

console.log(evenNumbers); // [2, 4]
Enter fullscreen mode Exit fullscreen mode

reduce()

The reduce() method executes a reducer function on each element of the array, resulting in a single output value. It's often used for summing values, accumulating totals, or merging arrays into a single value.

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

const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // 15
Enter fullscreen mode Exit fullscreen mode

find()

The find() method returns the value of the first element in the array that satisfies the provided testing function. It stops after finding the first match.

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

const found = array.find((element) => element > 3);

console.log(found); // 4
Enter fullscreen mode Exit fullscreen mode

findIndex()

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

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

const index = array.findIndex((element) => element > 3);

console.log(index); // 3
Enter fullscreen mode Exit fullscreen mode

sort()

The sort() method sorts the elements of an array in place and returns the sorted array. It's commonly used to sort strings and numbers, but it may require a compare function to sort numbers correctly.

const array = [5, 3, 8, 1, 2];

const sortedArray = array.sort((a, b) => a - b);

console.log(sortedArray); // [1, 2, 3, 5, 8]
Enter fullscreen mode Exit fullscreen mode

reverse()

The reverse() method reverses the elements of an array in place. The first array element becomes the last, and the last becomes the first.

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

const reversedArray = array.reverse();

console.log(reversedArray); // [5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

concat()

The concat() method is used to merge two or more arrays. It returns a new array, leaving the original arrays unchanged.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

const concatenatedArray = array1.concat(array2);

console.log(concatenatedArray); // [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

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).

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

const slicedArray = array.slice(1, 4);

console.log(slicedArray); // [2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

splice()

The splice() method changes the contents of an array by removing, replacing, or adding elements.

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

array.splice(2, 1, 6, 7);

console.log(array); // [1, 2, 6, 7, 4, 5]
Enter fullscreen mode Exit fullscreen mode

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];

array.push(4, 5);

console.log(array); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

pop()

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

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

const lastElement = array.pop();

console.log(lastElement); // 5
console.log(array); // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

shift()

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

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

const firstElement = array.shift();

console.log(firstElement); // 1
console.log(array); // [2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

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 = [2, 3, 4, 5];

array.unshift(1);

console.log(array); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

join()

The join() method creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string.

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

const joinedString = array.join('-');

console.log(joinedString); // "1-2-3-4-5"
Enter fullscreen mode Exit fullscreen mode

Additional Methods

every()

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

const array = [2, 4, 6, 8];

const allEven = array.every((element) => element % 2 === 0);

console.log(allEven); // true
Enter fullscreen mode Exit fullscreen mode

some()

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

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

const hasEven = array.some((element) => element % 2 === 0);

console.log(hasEven); // true
Enter fullscreen mode Exit fullscreen mode

flat()

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

const array = [1, [2, [3, [4]]]];

const flattenedArray = array.flat(2);

console.log(flattenedArray); // [1, 2, 3, [4]]
Enter fullscreen mode Exit fullscreen mode

flatMap()

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It's a combination of map() and flat().

const array = [1, 2, 3, 4];

const flattened = array.flatMap((num) => [num, num * 2]);

console.log(flattened); // [1, 2, 2, 4, 3, 6, 4, 8]
Enter fullscreen mode Exit fullscreen mode

fill()

The fill() method fills all the elements of an array with a static value from a start index to an end index.

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

array.fill(0, 2, 4);

console.log(array); // [1, 2, 0, 0, 5]
Enter fullscreen mode Exit fullscreen mode

copyWithin()

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

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

array.copyWithin(0, 3, 5);

console.log(array); // [4, 5, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

includes()

The includes() method checks if an array contains a certain value.

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

const hasThree =

 array.includes(3);

console.log(hasThree); // true
Enter fullscreen mode Exit fullscreen mode

toString()

The toString() method converts an array to a string, separated by commas.

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

const arrayString = array.toString();

console.log(arrayString); // "1,2,3,4,5"
Enter fullscreen mode Exit fullscreen mode

indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

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

const index = array.indexOf(3);

console.log(index); // 2
Enter fullscreen mode Exit fullscreen mode

lastIndexOf()

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.

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

const lastIndex = array.lastIndexOf(3);

console.log(lastIndex); // 4
Enter fullscreen mode Exit fullscreen mode

from()

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

const array = Array.from('hello');

console.log(array); // ['h', 'e', 'l', 'l', 'o']
Enter fullscreen mode Exit fullscreen mode

isArray()

The Array.isArray() method checks whether the passed value is an array.

const array = [1, 2, 3, 4, 5];
const notArray = { a: 1, b: 2 };

console.log(Array.isArray(array)); // true
console.log(Array.isArray(notArray)); // false
Enter fullscreen mode Exit fullscreen mode

of()

The Array.of() method creates a new array instance with a variable number of elements.

const array1 = Array.of(1, 2, 3);
const array2 = Array.of('a', 'b', 'c');

console.log(array1); // [1, 2, 3]
console.log(array2); // ['a', 'b', 'c']
Enter fullscreen mode Exit fullscreen mode

Conclusion

JavaScript arrays come with a wide range of built-in methods that allow for powerful data manipulation. Understanding these methods will make you more efficient in writing clean and concise code. Take some time to experiment with these methods and see how they can improve your code.
Originally Published: JavaScript Array Methods Guide

💖 💪 🙅 🚩
who_tf_cares
Kavei Sahai

Posted on September 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related