the most popular array methods in JavaScript that you don’t want to miss out on!
First, let's list the methods we will cover and then explain each one in detail. map() filter() reduce() forEach() find() findIndex() some() every() includes() indexOf() slice() splice() sort() join() 1 - map() The map() method is used to create a new array by transforming each element in the original array. It is important to note that it does not change the original array. const numbers = [1, 2, 3]; const doubled = numbers.map(x => x * 2); // [2, 4, 6] const users = [{ name: 'John' }, { name: 'Jane' }]; const names = users.map(user => user.name); // ['John', 'Jane'] 2 - filter() The filter() method is used to return a new array that contains elements meeting specific conditions. For example, you might want to filter an array of cars, returning only those with a number of wheels greater than 3, or filter a list of planes that have more than 2 engines. The original array remains unchanged. const nums = [1, 2, 3, 4, 5, 6]; const evenNums = nums.filter(n => n % 2 === 0); // [2, 4, 6] const products = [{ price: 10 }, { price: 20 }]; const expensive = products.filter(p => p.price > 15); // [{ price: 20 }] 3 - reduce() reduce() is one of the most important functions in JavaScript for working with arrays. To explain it simply, imagine you have two baskets of apples, and you want to count them. You take apples one by one from the first basket and place them into the second basket. The second basket acts as an accumulator, where you keep the total count of apples. Initially, this basket starts empty (or at zero). In code terms, it can be thought of as: [apple1, apple2, apple3].reduce((accumulator, currentApple) => accumulator + currentApple, 0); Here, apple1, apple2, and apple3 could be numbers, arrays, or objects based on your specific needs. const sum = [1, 2, 3].reduce((acc, curr) => acc + curr, 0); // 6 const cart = [{ price: 10 }, { price: 20 }]; const total = cart.reduce((sum, item) => sum + item.price, 0); // 30 I hope this clarifies how to use reduce(). 4 - forEach() forEach() is a close competitor of map(). It executes a provided function once for each element in the array. Once it starts iterating over the array, it cannot be stopped. Note that forEach() does not return a new array; it returns undefined. [1, 2, 3].forEach(n => console.log(n)); ['a', 'b'].forEach((item, index) => console.log(`${index}: ${item}`)); 5 - find() The find() method is similar to filter(), but instead of returning an array, it returns the first element that meets the specified condition and stops searching further. const users2 = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]; const john = users2.find(user => user.name === 'John'); // { id: 1, name: 'John' } const nums2 = [1, 2, 3, 4]; const firstEven = nums2.find(n => n % 2 === 0); // 2 6 - findIndex() The findIndex() method searches for the first element that meets a specified condition and returns its index. If no element is found, it returns -1. const fruits = ['apple', 'banana', 'cherry']; const bananaIndex = fruits.findIndex(f => f === 'banana'); // 1 const userIndex = users2.findIndex(u => u.id === 2); // 1 7 - some() The some() method checks if any elements in the array meet a specified condition. If at least one is found, it stops searching and returns true. const hasEven = [1, 2, 3].some(n => n % 2 === 0); // true const hasExpensive = products.some(p => p.price > 15); // true This should provide a clearer understanding of each method and its usage! 8 - every() The every() method checks if all elements in an array meet a specified condition. It returns true if all elements satisfy the condition, and false if even one element fails to meet it. const allPositive = [1, 2, 3].every(n => n > 0); // true const allCheap = products.every(p => p.price < 25); // true 9 - includes() The includes() method is used to check if an array contains a specific element. It checks for the presence of that element, which must be of the same type as the elements within the array. const numbers2 = [1, 2, 3]; const hasTwo = numbers2.includes(2); // true const hasZero = numbers2.includes(0); // false 10 - indexOf() The indexOf() method is used to find the index of a specific value within an array. Unlike findIndex(), which finds the index of the first element that meets a condition, indexOf() looks for the exact value. const colors = ['red', 'blue', 'green']; const blueIndex = colors.indexOf('blue'); // 1 const yellowIndex = colors.indexOf('yellow'); // -1 11 - slice() The slice() method is a crucial tool that you should master. It is used to cut a portion of the array without altering the original
First, let's list the methods we will cover and then explain each one in detail.
map()
filter()
reduce()
forEach()
find()
findIndex()
some()
every()
includes()
indexOf()
slice()
splice()
sort()
join()
1 - map()
The map()
method is used to create a new array by transforming each element in the original array. It is important to note that it does not change the original array.
const numbers = [1, 2, 3];
const doubled = numbers.map(x => x * 2); // [2, 4, 6]
const users = [{ name: 'John' }, { name: 'Jane' }];
const names = users.map(user => user.name); // ['John', 'Jane']
2 - filter()
The filter()
method is used to return a new array that contains elements meeting specific conditions. For example, you might want to filter an array of cars, returning only those with a number of wheels greater than 3, or filter a list of planes that have more than 2 engines. The original array remains unchanged.
const nums = [1, 2, 3, 4, 5, 6];
const evenNums = nums.filter(n => n % 2 === 0); // [2, 4, 6]
const products = [{ price: 10 }, { price: 20 }];
const expensive = products.filter(p => p.price > 15); // [{ price: 20 }]
3 - reduce()
reduce()
is one of the most important functions in JavaScript for working with arrays. To explain it simply, imagine you have two baskets of apples, and you want to count them. You take apples one by one from the first basket and place them into the second basket. The second basket acts as an accumulator, where you keep the total count of apples. Initially, this basket starts empty (or at zero).
In code terms, it can be thought of as:
[apple1, apple2, apple3].reduce((accumulator, currentApple) => accumulator + currentApple, 0);
Here, apple1
, apple2
, and apple3
could be numbers, arrays, or objects based on your specific needs.
const sum = [1, 2, 3].reduce((acc, curr) => acc + curr, 0); // 6
const cart = [{ price: 10 }, { price: 20 }];
const total = cart.reduce((sum, item) => sum + item.price, 0); // 30
I hope this clarifies how to use reduce()
.
4 - forEach()
forEach()
is a close competitor of map()
. It executes a provided function once for each element in the array. Once it starts iterating over the array, it cannot be stopped. Note that forEach()
does not return a new array; it returns undefined
.
[1, 2, 3].forEach(n => console.log(n));
['a', 'b'].forEach((item, index) => console.log(`${index}: ${item}`));
5 - find()
The find()
method is similar to filter()
, but instead of returning an array, it returns the first element that meets the specified condition and stops searching further.
const users2 = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
const john = users2.find(user => user.name === 'John'); // { id: 1, name: 'John' }
const nums2 = [1, 2, 3, 4];
const firstEven = nums2.find(n => n % 2 === 0); // 2
6 - findIndex()
The findIndex()
method searches for the first element that meets a specified condition and returns its index. If no element is found, it returns -1.
const fruits = ['apple', 'banana', 'cherry'];
const bananaIndex = fruits.findIndex(f => f === 'banana'); // 1
const userIndex = users2.findIndex(u => u.id === 2); // 1
7 - some()
The some()
method checks if any elements in the array meet a specified condition. If at least one is found, it stops searching and returns true
.
const hasEven = [1, 2, 3].some(n => n % 2 === 0); // true
const hasExpensive = products.some(p => p.price > 15); // true
This should provide a clearer understanding of each method and its usage!
8 - every()
The every()
method checks if all elements in an array meet a specified condition. It returns true
if all elements satisfy the condition, and false
if even one element fails to meet it.
const allPositive = [1, 2, 3].every(n => n > 0); // true
const allCheap = products.every(p => p.price < 25); // true
9 - includes()
The includes()
method is used to check if an array contains a specific element. It checks for the presence of that element, which must be of the same type as the elements within the array.
const numbers2 = [1, 2, 3];
const hasTwo = numbers2.includes(2); // true
const hasZero = numbers2.includes(0); // false
10 - indexOf()
The indexOf()
method is used to find the index of a specific value within an array. Unlike findIndex()
, which finds the index of the first element that meets a condition, indexOf()
looks for the exact value.
const colors = ['red', 'blue', 'green'];
const blueIndex = colors.indexOf('blue'); // 1
const yellowIndex = colors.indexOf('yellow'); // -1
11 - slice()
The slice()
method is a crucial tool that you should master. It is used to cut a portion of the array without altering the original array. It takes two parameters: the starting index and the stopping index (which is not included in the result). If you use a negative number, such as -1
, it counts back from the end of the array (-1
refers to the last element, and -2
refers to the second last).
const arr = [1, 2, 3, 4, 5];
const middle = arr.slice(1, 4); // [2, 3, 4]
const last = arr.slice(-2); // [4, 5]
12 - splice()
Be cautious when using splice()
because it does modify the original array. This method can add, remove, or replace elements. It consists of three parameters: (start index, number of elements to remove, items to add). If you do not specify the number of items to remove, you are adding elements. If you do not specify the items to add, you are simply deleting. Combining both will replace elements.
const months = ['Jan', 'March', 'April'];
months.splice(1, 0, 'Feb'); // ['Jan', 'Feb', 'March', 'April']
months.splice(2, 1); // ['Jan', 'Feb', 'April']
13 - sort()
The sort()
method is used to sort the elements of an array. By default, it sorts elements as strings. For more complex sorting, you can provide a compare function. Note that this method modifies the original array.
const unsorted = [3, 1, 4, 1, 5];
unsorted.sort((a, b) => a - b); // [1, 1, 3, 4, 5]
const names2 = ['Zack', 'Alice', 'Bob'];
names2.sort(); // ['Alice', 'Bob', 'Zack']
14 - join()
The join()
method converts each element of the array to a string and joins them together using a specified separator.
const elements = ['Fire', 'Air', 'Water'];
const result = elements.join(); // "Fire, Air, Water"
const result2 = elements.join(' - '); // "Fire - Air - Water"