Lesson 19 of 55
javascriptArray Methods – map, filter, reduce, find, some, every
12 mins
Course progress35%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 19 of 55
javascript12 mins
Keep these ideas in mind as you work through the lesson.
Functional array helpers make data transformation declarative.
const nums = [1,2,3,4,5];
const evens = nums.filter(n=>n%2===0); // [2,4]
const squares = nums.map(n=>n*n); // [1,4,9,16,25]
const sum = nums.reduce((a,b)=>a+b,0); // 15
Other useful methods:
find – first element matching a predicate.some – any element matches?every – all elements match?const books = [
{genre:'fiction',title:'A'},
{genre:'nonfiction',title:'B'},
{genre:'fiction',title:'C'}
];
const byGenre = books.reduce((acc,b)=>{
(acc[b.genre] = acc[b.genre] || []).push(b);
return acc;
},{});
console.log(byGenre);