Arrays are one of the most common data structures in JavaScript. Rather than writing imperative for loops, modern JavaScript provides powerful array methods that allow you to manipulate arrays declaratively. Let's master the most important ones.
1. Array.prototype.map()
Creates a new array populated with the results of calling a provided function on every element in the calling array. Excellent for transforming data.
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2); // [2, 4, 6]
2. Array.prototype.filter()
Creates a shallow copy of a portion of a given array, filtered down to just the elements that pass the test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0); // [2, 4]
3. Array.prototype.reduce()
Executes a user-supplied reducer callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0); // 10
4. Array.prototype.find() and findIndex()
find() returns the first element in the array that satisfies the provided testing function. findIndex() returns its index. If no values satisfy the testing function, they return undefined and -1 respectively.
const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
const user = users.find(u => u.id === 2); // {id: 2, name: 'Bob'}
5. Array.prototype.some() and every()
some() tests whether at least one element in the array passes the test. every() tests whether all elements pass the test. Both return boolean values.
const ages = [12, 18, 22, 15];
const hasAdults = ages.some(age => age >= 18); // true
const allAdults = ages.every(age => age >= 18); // false
6. Array.prototype.includes()
Determines whether an array includes a certain value among its entries, returning true or false.
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('banana')); // true