Lesson 19 of 55 · javascript
Array Methods – map, filter, reduce, find, some, every
Duration: 12 mins
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?
Example: Group objects by property
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);