Created
September 10, 2016 21:54
-
-
Save dengjonathan/117678ef41c4c34c0ac1ccf70cc3dbd0 to your computer and use it in GitHub Desktop.
map function
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
names2 = ['kendra', 'kim', 'kampbell']; | |
// use this as your callback function in map | |
var capitalize = function(word) { | |
return word[0].toUpperCase() + word.slice(1); | |
}; | |
// we need each implemented for map to work | |
var each = function(array, callback) { | |
for (var i = 0; i < array.length; i++) { | |
callback(array[i]); | |
} | |
}; | |
/* | |
QUESTION: create a map function that takes two arguments, an array, and a callback function, | |
and returns a new array with all the items in the array transformed using the callback function | |
*/ | |
var map = function(array, callback) { | |
var changes = []; | |
// call to each function with 2 args: array and callback function | |
each(array, function(each) { | |
changes.push(callback(each)); | |
}); | |
return changes; | |
} | |
map([1, 2, 3], function(e) { | |
return e + 1; | |
}); | |
map(names, capitalize); // ['Kendra', 'Kim', 'Kampbell'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment