CodePark/ questions / Arrays & objects
START PRACTICINGPRACTICE
Frontend question · JavaScript › Arrays & objects

Explain map, filter and reduce. When would you use each?

All three are array methods that take a callback and return a new value. None of them changes the original array.

  • map changes each element and returns a new array of the same length. Example: prices.map(p => p * 1.2).
  • filter returns a new array with only the elements where the callback returns a truthy value. Example: users.filter(u => u.active).
  • reduce combines the array into one value of any type. It carries an accumulator (a running result) from element to element. Example: items.reduce((sum, i) => sum + i.price, 0). It can build numbers, objects or maps.

Always give reduce an initial value. Without one, it uses the first element as the start. On an empty array, it throws a TypeError.

For side effects, like logging, use forEach or a normal loop. Clear map and filter chains are usually better than clever reduce calls.

  • map returns an array of the same length with changed elements.
  • filter returns the elements where the callback is truthy.
  • reduce builds one value of any shape using an accumulator.
  • All three return new values. The original array does not change.
  • Give reduce an initial value. Without one, an empty array throws.