🟒 EasyArraysπŸ“– Theory Question

When would you use map vs forEach vs reduce vs filter?

πŸ’‘

Hint

map=transform, filter=subset, reduce=accumulate, forEach=side effects

Full Answer

  • map β€” transform each element, returns new array of same length
  • filter β€” keep matching elements, returns smaller array
  • reduce β€” accumulate into single value (any type)
  • forEach β€” side effects only, returns undefined, not chainable
const nums = [1,2,3,4,5];
nums.map(n => n * 2);                // [2,4,6,8,10]
nums.filter(n => n % 2 === 0);       // [2,4]
nums.reduce((sum, n) => sum + n, 0); // 15

// Chaining
nums.filter(n => n > 2).map(n => n ** 2); // [9,16,25]

More Arrays Questions

🟒 EasyHow do Array.find(), findIndex(), some(), and every() work?β†’πŸŸ’ EasyHow do Array.flat() and Array.flatMap() work?β†’πŸŸ’ EasyWhat are immutable array operations and the new ES2023 methods?β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint