javascrip Map code example
Example 1: javascript map array
const myArray = ['Sam', 'Alice', 'Nick', 'Matt'];
const newArray = myArray.map(name => {
return 'My name is ' + name;
});
console.log(newArray);
const anotherArray = myArray.map((value, index) => index + ": " + value);
console.log(anotherArray);
console.log(myArray);
Example 2: javascript array transform
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
Example 3: maps in javascript
const obj1 = { name: 'ismail' };
const obj2 = { name: 'sulman' };
const obj3 = { name: 'naeem' };
firstMap = new Map([
[
[obj1, [{ date: 'yesterday', price: '10$' }]],
[obj2, [{ date: 'today', price: '100$' }]]
]
]);
firstMap.set(obj3, [{ date: "yesterday", price: '150$' }]);
for (const entry of firstMap.entries()) {
console.log(entry);
};
console.log(firstMap);
firstMap.delete(obj3);
console.log(firstMap);
Example 4: map in javascript
const arr = [1,2,3,4]
const sqrs = arr.map((num) => num ** 2)
console.log(sqrs)
console.log(arr)
Example 5: map javascript
function each(collection, action) {
if (Array.isArray(collection)) {
for (var i = 0; i < collection.length; i++) {
action(collection[i], i, collection);
}
} else {
for (var key in collection) {
action(collection[key], key, collection);
}
}
}
Example 6: map in javascript
['elem', 'another', 'name'].map((value, index, originalArray) => {
console.log(.....)
});