mapsin javascript code example

Example 1: maps in javascript

// Map decalaration in javaScript
const obj1 = { name: 'ismail' };
const obj2 = { name: 'sulman' };
const obj3 = { name: 'naeem' };

firstMap = new Map([
    [
        [obj1, [{ date: 'yesterday', price: '10$' }]], // using object as a key in the map and object inside the array
        [obj2, [{ date: 'today', price: '100$' }]]
    ]
]);
firstMap.set(obj3, [{ date: "yesterday", price: '150$' }]); //pushing the obj to the Map

// iterating the Map
for (const entry of firstMap.entries()) {
    console.log(entry);
};

console.log(firstMap);

firstMap.delete(obj3);
console.log(firstMap);

Example 2: map javascript

function map(collection, action) {
  let result = [];
  if (Array.isArray(collection)) {
    for (let i = 0; i < collection.length; i++) {
      result.push(action(collection[i], i, collection));
    }
  }
  else {
    for (let key in collection) {
      result.push(action(collection[key], key, collection));
    }
  } return result;
}