Created
January 18, 2017 20:57
-
-
Save bertoort/9543b89eb1779e6c3784fcd4f207361a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Objective - Describe and implement the following native array methods: | |
// forEach, some, every, filter, map, and reduce. | |
// FOREACH | |
// There are a number of helpful functions built-in | |
// to JavaScript's regular arrays. These methods | |
// are both higher order functions and **functional** | |
// in that they do not manipulate the array they | |
// are working on. That is, they are non-destructive. | |
// The simplest example is .forEach | |
var array = [ 10, 20, 30, 40 ] | |
var returnValue = array.forEach(function (element, index, collection) { | |
return console.log('At ' + index + ':', element, collection) | |
}) | |
// .forEach is simply to create side effects. It does | |
// not return any value unlike the other native array | |
// methods we'll discuss today. | |
// Notice that the original array hasn't changed in any way! | |
console.log('---\nOriginal array:', array) | |
// All of the native array method callback functions | |
// have a similar function signature. They typically | |
// include placeholder for the element(s), index, and | |
// then array. You can include all or none of these | |
// parameters -- although you should probably include | |
// at least one of them! | |
var vegetables = [ 'Cucumber', 'Carrot', 'Kale' ] | |
vegetables.forEach(function (vegetable) { | |
if (vegetable === 'Kale') console.log('Kale is trendy.') | |
console.log(vegetable, 'is a pretty standard vegetable') | |
}) | |
// Remember that since functions are first class citizens | |
// we can assign them to variables and pass them around! | |
function kaleIsTrendy(vegetable) { | |
if (vegetable === 'Kale') console.log('Kale is trendy.') | |
console.log(vegetable, 'is a pretty standard vegetable') | |
} | |
vegetables.forEach(kaleIsTrendy) | |
// Let's practice. Write a function that, for each element | |
// in the following array, prints out its square. | |
var numbers = [ 2, 4, 8, 16, 32 ] | |
// SOME AND EVERY | |
// .some and .every turn an array into a boolean | |
// value. They check that at least one element in | |
// the array matches a conditional or that every | |
// element in the array matches a conditional, | |
// respectively. | |
function isTruthy (element) { | |
return !!element | |
} | |
var array = [ true, false, false ] | |
var someResult = array.some(isTruthy) | |
var everyResult = array.every(isTruthy) | |
// console.log(someResult) | |
// console.log(everyResult) | |
// One cool thing about these methods is that they | |
// return immediately as soon as they have the answer. | |
function isNegative (num) { | |
console.log(num) | |
return num < 0 | |
} | |
var array = [ 20, 10, 0, -10, -20 ] | |
var someResult = array.some(isNegative) | |
var everyResult = array.every(isNegative) | |
console.log(someResult) | |
console.log(everyResult) | |
// Let's practice. Write a function that checks to see if | |
// all the following words have a vowel (aeiou) in them. | |
// Use the same check but with `.some`. | |
var words = [ | |
'aromatic', | |
'energetic', | |
'ugly', | |
'wry' | |
] | |
// FILTER | |
// .filter also uses a conditional statement but it | |
// goes through a list of items and returns between | |
// 0 - N number of items back depending upon the | |
// given conditional. It's incredibly useful for | |
// whittling down large arrays so that we only pick | |
// out those items we want! | |
var characters = [ | |
{ character: 'Superman', hero: true }, | |
{ character: 'Sinestro', hero: false }, | |
{ character: 'Wonder Woman', hero: true }, | |
{ character: 'Lex Luthor', hero: false }, | |
{ character: 'Green Lantern', hero: true } | |
] | |
function isHero (character) { | |
return character.hero | |
} | |
var heroes = characters.filter(isHero) | |
console.log(heroes) | |
// Let's practice. Write a function that takes the following | |
// numbers and returns only those numbers that are divisible | |
// by 3. | |
var numbers = [ 12, 10, 6, 5, 3, 2, 1 ] | |
// MAP | |
// Map works by returning a new array after a function | |
// has been applied to every single element in the array. | |
// It will always return the same number of elements | |
// that is in the array it works on. | |
var familyMembers = [ | |
{ firstName: 'Homer', lastName: 'Simpson' }, | |
{ firstName: 'Marge', lastName: 'Simpson' }, | |
{ firstName: 'Bart', lastName: 'Simpson' }, | |
{ firstName: 'Lisa', lastName: 'Simpson' }, | |
{ firstName: 'Maggie', lastName: 'Simpson' } | |
] | |
function getFirstName (person) { | |
return person.firstName | |
} | |
var firstNames = familyMembers.map(getFirstName) | |
console.log(firstNames) | |
// Let's practice. Take the following array and return | |
// the length of each item inside of it. | |
var array = [ | |
[ 10, 0, 20 ], | |
'catchphrase!', | |
Date.now().toString() | |
] | |
// REDUCE | |
// Reduce is an incredibly powerful method that allows | |
// us to combine all of the result in an array into a | |
// single result. There are a few different ways we | |
// can use it, so it's important to read the | |
// documentation carefully! | |
// Let's take the following array as an example. | |
var epic = [ | |
'a', 'long', 'time', 'ago', 'in a', 'galaxy', 'far far', 'away' | |
] | |
// With `.reduce()`, we can combine all of these into | |
// a single string! You'll typically use reduce with | |
// two arguments: previous and current (also known as | |
// accumulator and current). In this case, reduce starts | |
// with giving you access to the first two elements of the | |
// array (i.e. 'a' and 'long'). You then returns a *single* | |
// value which becomes previous in the next iteration while | |
// current changes to be the next item in the array (i.e. 'time') | |
function concatenate (message, element, index, collection) { | |
return message + ' ' + element | |
} | |
var result = epic.reduce(concatenate) | |
console.log(result) | |
// It may take a minute to get your mind wrapped around | |
// what's happening. However, by simply logging the values | |
// it (hopefully!) becomes much more clear what's going on. | |
// epic.reduce(function (previous, current) { | |
// console.log('logging -- current: "' + current + '", ' + 'previous: "' + previous + '"') | |
// return previous + ' ' + current | |
// }) | |
// Let's get back to our users and see how we can actually | |
// set the initial value for our reduce method! | |
var users = [ | |
{ fullName: 'George Washington', email: '[email protected]' }, | |
{ fullName: 'John Adams', email: '[email protected]' }, | |
{ fullName: 'Thomas Jefferson', email: '[email protected]' }, | |
{ fullName: 'James Madison', email: '[email protected]' } | |
] | |
// We want to change up the structure of our users so that | |
// we can use the users' full name as the key and have their | |
// email as the value. Normally, this would take a lot of | |
// looping and initializing some variables. However, with | |
// reduce we can set an empty object as our starting point | |
// (i.e. previous) and do it all in a single go! | |
function createEmailObject (accumulator, user, index) { | |
accumulator[user.fullName] = user.email | |
return accumulator | |
} | |
var result = users.reduce(createEmailObject, {}) | |
console.log(result) | |
// Notice how our initial value comes after the function | |
// is passed into reduce. | |
// Let's practice. Take the following array and multiply | |
// all the numbers together! | |
var fiveFactorial = [ 5, 4, 3, 2, 1 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment