Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Last active February 23, 2018 15:44
Show Gist options
  • Save ryasmi/40afd81a66186623b980bd501a1cfc62 to your computer and use it in GitHub Desktop.
Save ryasmi/40afd81a66186623b980bd501a1cfc62 to your computer and use it in GitHub Desktop.
JS Mushroom Episode 1 - Array Functions (2018-02-09)
// Using forEach.
[1,2,3].forEach((item, index, items) => {
console.log('item', item); // Logs "1" for the first item, "2" for the second item, and "3" for the third item.
console.log('index', index); // Logs "0" for the first item, "1" for the second item, and "2" for the third item.
console.log('items', items); // Logs "[1,2,3]" to the console for every item.
});
// Using map to add one to each item in an array.
const plusOneItems = [1,2,3].map((item, index, items) => {
return item + 1;
});
console.log('plusOneItems', plusOneItems); // Logs "[2,3,4]" to the console.
// Using filter to get even items from an array.
const evenItems = [1,2,3].filter((item, index, items) => {
const isEven = item % 2 === 0;
return isEven;
});
console.log('evenItems', evenItems); // Logs "[2]" to the console.
// Using reduce to sum all of the items in the array.
const sum = [1,2,3].reduce((carry, item, index, items) => {
console.log('carry', carry); // Logs "0" for the first item, "1" for the second item", and "3" for the third item.
return carry + item;
}, 0);
console.log('sum', sum); // Logs "6" to the console.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment