5 min read
•Question 12 of 50mediumExplain map, filter, and reduce array methods
Understanding functional array methods.
What You'll Learn
- map() for transformation
- filter() for selection
- reduce() for accumulation
map()
Creates a new array by transforming each element.
code.jsJavaScript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8]
const users = [{ name: 'John' }, { name: 'Jane' }];
const names = users.map(user => user.name);
// ['John', 'Jane']filter()
Creates a new array with elements that pass the test.
code.jsJavaScript
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4, 6]
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 17 }
];
const adults = users.filter(u => u.age >= 18);
// [{ name: 'John', age: 25 }]reduce()
Reduces array to a single value.
code.jsJavaScript
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 10
// Group by property
const people = [
{ name: 'John', city: 'NYC' },
{ name: 'Jane', city: 'LA' },
{ name: 'Bob', city: 'NYC' }
];
const byCity = people.reduce((acc, person) => {
acc[person.city] = acc[person.city] || [];
acc[person.city].push(person);
return acc;
}, {});Chaining
code.jsJavaScript
const result = numbers
.filter(n => n > 2)
.map(n => n * 2)
.reduce((acc, n) => acc + n, 0);