Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Created September 10, 2016 21:54
Show Gist options
  • Save dengjonathan/117678ef41c4c34c0ac1ccf70cc3dbd0 to your computer and use it in GitHub Desktop.
Save dengjonathan/117678ef41c4c34c0ac1ccf70cc3dbd0 to your computer and use it in GitHub Desktop.
map function
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