Skip to content

Instantly share code, notes, and snippets.

@Vincent-gv
Created December 15, 2018 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vincent-gv/258e41d5bdad994f950afa38ea81bc4f to your computer and use it in GitHub Desktop.
Save Vincent-gv/258e41d5bdad994f950afa38ea81bc4f to your computer and use it in GitHub Desktop.
.forEach() .map() .filter() .reduce()
// .forEach()
const artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];
artists.forEach(artist => {
console.log(artist + ' is one of my favorite artists.');
});
// expected output:
// "Picasso is one of my favorite artists."
// "Kahlo is one of my favorite artists."
// "Matisse is one of my favorite artists."
// "Utamaro is one of my favorite artists."
// .map()
const numbers = [1, 2, 3, 4, 5];
const squareNumbers = numbers.map(number => {
return number * number;
});
console.log(squareNumbers);
// expected output: [1, 4, 9, 16, 25]
// .filter()
const things = ['desk', 'chair', 5, 'backpack', 3.14, 100];
const onlyNumbers = things.filter(thing => {
return typeof thing === 'number';
});
console.log(onlyNumbers);
// expected output: [5, 3.14, 100]
// .reduce()
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment