0
Q:

js 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 }; });
2
/* Answer to: "javascript map function" */

/*
  <Array>.map() - One of the most useful in-built methods in JavaScript (imo).

  The map() method creates a new array populated with the results of calling
  a provided function on every element in the calling array.
 
  For more information, click on the source link.

  Let me make some examples of it's uses:
*/

let array = [1, 4, 9, 16];
array.map(num => num * 2); // [2, 8, 18, 32];
array.map(pounds => `£${pounds}.00`); // ["£1.00", "£4.00", "£9.00", "£16.00"];
array.map(item => Math.sqrt(item)); // [1, 2, 3, 4];
3
const map = new Map();

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

map.set("foo", foo);

console.log(map.get("foo")()); // Output: "Hello World!
3
const array1 = [1, 4, 9, 16];

var map1 = array1.map(x => x * 2);
var map2 = array1.map( function( x, i ) {
  	console.log(x, i);
  	// x = 1 , 4 , 9 ,16 i = 0 , 1 , 2 , 3
    return x
} ); 
console.log(map1);
// expected output: Array [2, 8, 18, 32]
3
const arr = [1,2,3];
const mapped = arr.map(x => x * x);
4
const exampleArray = ['aa','bbc','ccdd'];
console.log(exampleArray.map(a => a.length));
//Would print out [2,3,4]
3
let new_array = arr.map(function callback( currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])
0

New to Communities?

Join the community