es6 map function code example

Example 1: javascript map function

const posts = [
  { id: 1, title: "Sample Title 1", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." },
  { id: 2, title: "Sample Title 2", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." },
  { id: 3, title: "Sample Title 3", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." },
];
// ES2016+
// Create new array of post IDs. I.e. [1,2,3]
const postIds = posts.map((post) => post.id);
// Create new array of post objects. I.e. [{ id: 1, title: "Sample Title 1" }]
const postSummaries = posts.map((post) => ({ id: post.id, title: post.title }));

// ES2015
// Create new array of post IDs. I.e. [1,2,3]
var postIds = posts.map(function (post) { return post.id; });
// Create new array of post objects. I.e. [{ id: 1, title: "Sample Title 1" }]
var postSummaries = posts.map(function (post) { return { id: post.id, title: post.title }; });

Example 2: array map javascript

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Example 3: array map

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Example 4: how the map function works javascript

const array = [2, 5, 9];
let squares = array.map((num) => num * num);

console.log(array); // [2, 5, 9]
console.log(squares); // [4, 25, 81]

Example 5: functions in map javascript

const map = new Map();

function foo() {
 return "Hello World!"; 
}

map.set("foo", foo);

console.log(map.get("foo")()); // Output: "Hello World!

Example 6: map in javascript

let myMap = new Map()

let keyString = 'a string'
let keyObj    = {}
// setting the values
myMap.set(keyString, "value associated with 'a string'")
myMap.set(keyObj, 'value associated with keyObj')
myMap.set(keyFunc, 'value associated with keyFunc')
myMap.size              // 3
// getting the values
myMap.get(keyString)    // "value associated with 'a string'"
myMap.get(keyObj)       // "value associated with keyObj"
myMap.get(keyFunc)      // "value associated with keyFunc"