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

var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
  return num * 2;
});
// doubles is now [2, 8, 18]. numbers still [1, 4, 9]

Example 4: javascript map

array.map( item => item.id )

array2.map( item => item.toString() )

array2.map( item => item * 3 )

// this will apply a transformation to all elements of an array
// "" item => something "" is the transformation (function)

Example 5: map function javascript

var rebels = pilots.filter(function (pilot) {  return pilot.faction === "Rebels";});var empire = pilots.filter(function (pilot) {  return pilot.faction === "Empire";});

Example 6: como fazer map em javascript

// Exemplo 1
const apresentacao = ['Ilan', 'Daniela'];
// ['Ilan', 'Daniela']
apresentacao.map(nome => `Olá, ${nome}. Bem-vind@ :)`);
// ["Olá, Ilan. Bem-vind@ :)", "Olá, Daniela. Bem-vind@ :)"]

// Exemplo 2
const apresentacao = [2, 4, 6, 8];
// [2, 4, 6, 8]
apresentacao.map(num => `${num}^2 = ${num**2}`)
(5) ["2^2 = 4", "4^2 = 16", "6^2 = 36", "8^2 = 64"]