Last active
July 15, 2021 20:36
-
-
Save tekul/68de3c5fdaec638bd5b05b6b6ba5aea4 to your computer and use it in GitHub Desktop.
CYF array.map discussion
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
// We want to apply a function to each element of an array and get | |
// back a new array of the same length, with a function applied to | |
// each element. | |
let arr = [1, 2, 3, 4, 5]; | |
console.log(arr); | |
// Then function takes one parameter (same type as the elements in | |
// the array) and has to return something (or we end up with an | |
// array of "undefined" values). | |
function addOne(n) { | |
return n+1; | |
} | |
// We can do it using a for loop | |
let arr2 = []; | |
for(i=0; i < arr.length; i++) { | |
let newElement = addOne(arr[i]); | |
arr2.push(newElement); | |
} | |
console.log(arr2); | |
// But arr.map gives us the same result and is much simpler and | |
// easier to read | |
let arr3 = arr.map(addOne); | |
console.log(arr3); | |
// It works with strings too | |
let names = ["Virginie", "Andy", "Tara"]; | |
function upperCase(s) { | |
return s.toUpperCase();; | |
} | |
console.log(names.map(upperCase)); | |
// What's going on inside map is the same as our original for loop | |
// version | |
function myMap(f, someArray) { | |
let arr2 = []; | |
for(i=0; i < someArray.length; i++) { | |
let newElement = f(someArray[i]); | |
arr2.push(newElement); | |
} | |
return arr2; | |
} | |
let arr4 = myMap(addOne, arr); | |
console.log(arr4); | |
// The tricky thing is that we are passing a function as a parameter | |
// to the function, rather than calling the function ourselves. map calls | |
// the function for us. | |
function doSomethingToANumber(f, n) { | |
return f(n); | |
} | |
console.log(doSomethingToANumber(addOne, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment