Skip to content

Instantly share code, notes, and snippets.

@benmccormick
Created December 24, 2015 04:08
Show Gist options
  • Save benmccormick/e6d784120a439b95fe0e to your computer and use it in GitHub Desktop.
Save benmccormick/e6d784120a439b95fe0e to your computer and use it in GitHub Desktop.
Array.prototype functional methods
let arr = [1, 2, 3];
function log(item) {
console.log(item);
}
//forEach performs an action on each item
//in an array
arr.forEach(log); //logs 1 2 3 in order
function increment(num) {
return num + 1;
}
//map transforms each item in an array and
//returns new array with the transformed
//values leaving the original unchanged
arr.map(increment) // [2, 3, 4]
function isEven(num) {
return num % 2 === 0;
}
//filter creates a new array with the
//values for which the filter function
//returns a truthy value
arr.filter(isEven) // [2]
function add(a, b) {
return a + b;
}
//reduce iterates over an array and combines
//the values down into a single value
arr.reduce(add, 0) // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment