All three are array methods that take a callback and return a new value. None of them changes the original array.
mapchanges each element and returns a new array of the same length. Example:prices.map(p => p * 1.2).filterreturns a new array with only the elements where the callback returns a truthy value. Example:users.filter(u => u.active).reducecombines 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.
mapreturns an array of the same length with changed elements.filterreturns the elements where the callback is truthy.reducebuilds one value of any shape using an accumulator.- All three return new values. The original array does not change.
- Give
reducean initial value. Without one, an empty array throws.
Read more