JavaScript Array Methods#
Arrays are one of the most commonly used data structures in JavaScript. Here are the most important methods.
Transformation Methods
map()
Transforms each element of the array by applying a function:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]
filter()
Filters elements that meet a condition:
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]
reduce()
Reduces the array to a single value:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15
Search Methods
find()
Finds the first element that meets the condition:
const users = [
{ id: 1, name: 'Ana' },
{ id: 2, name: 'John' }
];
const user = users.find(u => u.id === 2);
// { id: 2, name: 'John' }
includes()
Checks if an element exists in the array:
const fruits = ['apple', 'banana', 'orange'];
fruits.includes('banana'); // true
Best Practices
- Use
map()when you need to transform all elements - Use
filter()when you need to filter elements - Use
find()when looking for a single element - Avoid modifying the original array when possible