forEach/filter/map/reduce

What is it about

  • Array methods
    • Available via the Array prototype
  • Alternative to using loops
  • Comes from functional programming

Why?

  • Increases readability compared to using loops
  • Easier to use
  • Doesn’t mutate the original data
/* forEach() */

// Executes a provided function once for each array element.
let array = [1,2,3];
array.forEach(function(item){
  console.log(item); // -> 1 // -> 2 // -> 3
});

Examples

// Compared to a for loop
let array = [2,4,6];
for (var i = 0; i < array.length; i++){
  console.log(array[i]);
}
/* map() */

// Creates a new array with the results of calling a provided
// function on every array element.

const numbers = [2, 4, 8, 10];
const doubles = numbers.map(x => x * 2);

console.log(doubles); // -> [4, 8, 16, 20]
/* filter() */

// Creates a new array with all elements that pass the condition
// implemented in the provided function.

const words = ['destruction', 'spray', 'limit', 'elite', 'exuberant'];
const longWords = words.filter(word => word.length > 6);

console.log(longWords); // -> ['exuberant', 'destruction']
/* reduce() */

// Applies a function against an accumulator and each element
// in the array to reduce it to a single value.

const items = [1, 2, 3, 4];
const sum = items.reduce((acc, value) => acc + value)

console.log(sum); // -> 10

forEach/filter/map/reduce

By Michael Kühnel

forEach/filter/map/reduce

A short overview about the Array Prototype methods forEach(), filter(), map(), reduce()

  • 871