javascritp map code example

Example 1: javascript map array

const myArray = ['Sam', 'Alice', 'Nick', 'Matt'];

// Appends text to each element of the array
const newArray = myArray.map(name => {
	return 'My name is ' + name; 
});
console.log(newArray); // ['My name is Sam', 'My Name is Alice', ...]

// Appends the index of each element with it's value
const anotherArray = myArray.map((value, index) => index + ": " + value);
console.log(anotherArray); // ['0: Sam', '1: Alice', '2: Nick', ...]

// Starting array is unchanged
console.log(myArray); // ['Sam', 'Alice', 'Nick', 'Matt']

Example 2: 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 3: javascript map function

/* 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];

Example 4: map in javascript

// Use map to create a new array in memory. Don't use if you're not returning
const arr = [1,2,3,4]

// Get squares of each element
const sqrs = arr.map((num) => num ** 2)
console.log(sqrs)
// [ 1, 4, 9, 16 ]

//Original array untouched
console.log(arr)
// [ 1, 2, 3, 4 ]

Example 5: javascript map array

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 6: javascript map

// The map() method creates a new array populated with the 
// results of calling a provided function on every element
// in the calling array.
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]