I got this array,
var rockets = [ { country:'Russia', launches:32 }, { country:'US', launches:23 }, { country:'China', launches:16 }, { country:'Europe(ESA)', launches:7 }, { country:'India', launches:4 }, { country:'Japan', launches:3 } ];
What do I need to do to return an array mapped, that adds 10 to each
launches
value, here my first approach,
var launchOptimistic = rockets.map(function(elem){ // return elem.launches+10; return (elem.country, elem.launches+10); }); console.log(launchOptimistic);
. map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in the callback function.
Return Value: It returns a new array and elements of arrays are result of callback function. Below examples illustrate the use of array map() method in JavaScript: Example 1: This example use array map() method and return the square of array element.
map() does not change the original array. It will always return a new array.
Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended
const rockets = [ { country:'Russia', launches:32 }, { country:'US', launches:23 }, { country:'China', launches:16 }, { country:'Europe(ESA)', launches:7 }, { country:'India', launches:4 }, { country:'Japan', launches:3 } ]; const launchOptimistic = rockets.map(elem => ( { country: elem.country, launches: elem.launches+10 } )); console.log(launchOptimistic);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With