javascript map key array code example
Example 1: javascript map
array.map((item) => {
return item * 2
}
Example 2: 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 3: javascript compare maps
"use strict";
function compareMaps(map1, map2) {
var testVal;
if (map1.size !== map2.size) {
return false;
}
for (var [key, val] of map1) {
testVal = map2.get(key);
if (testVal !== val || (testVal === undefined && !map2.has(key))) {
return false;
}
}
return true;
}
var o = {"k" : 2}
var m1 = new Map();
m1.set("obj", o);
m1.set("str0", undefined);
m1.set("str1", 1);
m1.set("str2", 2);
m1.set("str3", 3);
var m2 = new Map();
m2.set("str0", undefined);
m2.set("obj", o);
m2.set("str1", 1);
m2.set("str2", 2);
m2.set("str3", 3);
log(compareMaps(m1, m2));
m1.set("str-undefined", undefined);
m2.set("str4", 4);
log(compareMaps(m1, m2));
m1.delete("str-undefined");
log(compareMaps(m1, m2));
m1.set("str4", 5);
log(compareMaps(m1, m2));
function log(args) {
var str = "";
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === "object") {
str += JSON.stringify(arguments[i]);
} else {
str += arguments[i];
}
}
var div = document.createElement("div");
div.innerHTML = str;
var target = log.id ? document.getElementById(log.id) : document.body;
target.appendChild(div);
}