map
: Creates a new array
Iterates through an array
Runs a callback function for each value in the array
Adds the result of that callback function to the new array
Returns the new array
function map(array, callback){
var newArr = [];
for(var i = 0; i < array.length; i++){
newArr.push(callback(array[i], i, array));
}
return newArr;
}
/*
Write a function called doubleValues which accepts an array and returns a new array with all the values in the array passed to the function doubled
Examples:
doubleValues([1,2,3]) // [2,4,6]
doubleValues([1,-2,-3]) // [2,-4,-6]
*/
function doubleValues(arr){
var newArr = [];
arr.map(function(val, i, arr){ > return arr.map(function(val){
return val * 2;
}) });
} }
/*
Write a function called valTimesIndex which accepts an array and returns a new array with each value multiplied by the index it is currently at in the array.
Examples:
valTimesIndex([1,2,3]) // [0,2,6]
valTimesIndex([1,-2,-3]) // [0,-2,-6]
*/
function valTimesIndex(arr){
return arr.map(function(val, i , arr){
return val * i;
})
}
/*
Write a function called extractKey which accepts an array of objects and some key and returns a new array with the value of that key in each object.
Examples:
extractKey([{name: 'Elie'}, {name: 'Tim'}, {name: 'Matt'}, {name: 'Colt'}], 'name') // ['Elie', 'Tim', 'Matt', 'Colt']
*/
function extractKey(arr, key){
return arr.map(function(val){
return val[key];
})
}
/*
Write a function called extractFullName which accepts an array of objects and returns a new array with the value of the key with a name of "first" and the value of a key with the name of "last" in each object, concatenated together with a space.
Examples:
extractFullName([{first: 'Elie', last:"Schoppik"}, {first: 'Tim', last:"Garcia"}, {first: 'Matt', last:"Lane"}, {first: 'Colt', last:"Steele"}]) // ['Elie Schoppik', 'Tim Garcia', 'Matt Lane', 'Colt Steele']
*/
function extractFullName(arr, key){
return arr.map(function(val){
return val[key] > return val.first + " " + val.last;
})
}
'Udemy > Web Dev BootCamp' 카테고리의 다른 글
Advanced Array Methods(some & every) (0) | 2019.02.20 |
---|---|
Advanced Array Methods(filter) (0) | 2019.02.19 |
Advanced Array Methods(forEach) (0) | 2019.02.19 |
4 Ways AJAX(xhr / fetch / jquery / axios) (0) | 2019.02.18 |
Fetch Random User Profile Generator 코드리뷰 (0) | 2019.02.17 |