.map() with call back function
.map() accepts a callback function as one of its arguments, and an important parameter of that function is the current value of the item being processed by the function. This is a required parameter. With this parameter, we can modify each individual item in an array and create a new function off of it.
const numbers = [1,2,3,4,5]; const newNumbers = numbers.map(number => { return number*2; }); console.log(numbers); // will print [1,2,3,4,5] console.log(newNumbers); // will print [2,4,6,8,10]
Another way to to do this iteration
// create a function to use const newNumbers = number => number * 2; // we have an array const numbers = [1, 2, 3, 4, 5]; // call the function we made. more readable const numbers = numbers.map(newNumbers); console.log(newNumbers); // [2, 4, 6, 8, 10]
Convert an string to array using map function
const name = "John" const map = Array.prototype.map const nameArray = map.call(name, eachLetter => { return eachLetter; }) console.log(nameArray) // ["J", "o", "h", "n"]
Reformatting array object in Javascript using map function
const userLikes = [ { name: 'shark', likes: 'ocean' }, { name: 'turtle', likes: 'pond' }, { name: 'otter', likes: 'fish biscuits' } ] const userLikeAge = userLikes.map(user => { const container = {}; container[user.name] = user.likes; container.age = user.name.length * 10; return container; }) console.log(userLikeAge); // [{shark: "ocean", age: 50}, {turtle: "pond", age: 60}, {otter: "fish biscuits", age: 50}]
Map function to iterate an Javascript object
var myObject = { 'a': 1, 'b': 2, 'c': 3 }; Object.keys(myObject).map((key, index) => { myObject[key] *= 2; }); console.log(myObject); // => { 'a': 2, 'b': 4, 'c': 6 }