DEV Community

Discussion on: Explain it to me like I'm five: .map, .reduce, & .filter edition

Collapse
 
lexlohr profile image
Alex Lohr • Edited

Imagine you have small machines attached to arrays that take a function and use the array to do stuff with it.

  • map: this will take each item of the array it is attached to, runs it through the function and will return a new array with the results:

    [1, 2, 3].map(x => x + 1) // [2, 3, 4]
    
  • reduce: very much the same as map, but instead of an array, it will provide the function with the result of the last operation (or at the start the second argument it received) and returns the single last result instead of an array:

    [1, 2, 3].reduce((r, x) => r + x, 0) // 6
    
  • filter: this will return an array of all the values of the array it was attached to that had the function return a true-ish result:

    [1, 2, 3].filter(x => x % 2 === 1) // [1, 3]