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..." },
];
const postIds = posts.map((post) => post.id);
const postSummaries = posts.map((post) => ({ id: post.id, title: post.title }));
var postIds = posts.map(function (post) { return post.id; });
var postSummaries = posts.map(function (post) { return { id: post.id, title: post.title }; });
Example 2: array map javascript
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
Example 3: array map
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
Example 4: how the map function works javascript
const array = [2, 5, 9];
let squares = array.map((num) => num * num);
console.log(array);
console.log(squares);
Example 5: functions in map javascript
const map = new Map();
function foo() {
return "Hello World!";
}
map.set("foo", foo);
console.log(map.get("foo")());
Example 6: map in javascript
let myMap = new Map()
let keyString = 'a string'
let keyObj = {}
myMap.set(keyString, "value associated with 'a string'")
myMap.set(keyObj, 'value associated with keyObj')
myMap.set(keyFunc, 'value associated with keyFunc')
myMap.size
myMap.get(keyString)
myMap.get(keyObj)
myMap.get(keyFunc)