xxxxxxxxxx
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
xxxxxxxxxx
array.map((item) => {
return item * 2
} // an example that will map through a a list of items and return a new array with the item multiplied by 2
xxxxxxxxxx
const numbers = [1, 2, 3, 4, 5];
const bigNumbers = numbers.map(number => {
return number * 10;
});
xxxxxxxxxx
const numbers = [1, 4, 9];
const roots = numbers.map((num) => Math.sqrt(num));
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
xxxxxxxxxx
const numbers = [0,1,2,3];
console.log(numbers.map((number) => {
return number;
}));
xxxxxxxxxx
/* Answer to: "javascript map function" */
/*
<Array>.map() - One of the most useful in-built methods in JavaScript (imo).
The map() method creates a new array populated with the results of calling
a provided function on every element in the calling array.
For more information, click on the source link.
Let me make some examples of it's uses:
*/
let array = [1, 4, 9, 16];
array.map(num => num * 2); // [2, 8, 18, 32];
array.map(pounds => `£${pounds}.00`); // ["£1.00", "£4.00", "£9.00", "£16.00"];
array.map(item => Math.sqrt(item)); // [1, 2, 3, 4];
xxxxxxxxxx
// Map objects are collections of key-value pairs.
// A key in the Map may only occur once, it is unique in the Map 's collection
let map = new Map()
let keyArray = 'Array'
map.set(keyArray, [1, 2, 3, 4, 5])
map.get(keyArray) // 1, 2, 3, 4, 5
xxxxxxxxxx
// make new array from edited items of another array
var newArray = unchangedArray.map(function(item, index){
return item; // do something to returned item
});
// same in ES6 style (IE not supported)
var newArray2 = unchangedArray.map((item, index) => item);
xxxxxxxxxx
const numbers = [2, 4, 6, 8];
const result = numbers.map(a => a * 2);
console.log(result);
//Output: [ 4, 8, 12, 16 ]
xxxxxxxxxx
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const anotherItems = items.map(item => item * 2);
console.log(anotherItems);
How to use Map Function in Javascript
xxxxxxxxxx
const map1 = new Map();
map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);
console.log(map1.get('a'));
// Expected output: 1
map1.set('a', 97);
console.log(map1.get('a'));
// Expected output: 97
console.log(map1.size);
// Expected output: 3
map1.delete('b');
console.log(map1.size);
// Expected output: 2