,map js 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: 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: 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"

Example 4: map in javascript

['elem', 'another', 'name'].map((value, index, originalArray) => { 
  console.log(.....)
});

Example 5: map javascript

var kvArray = [["clave1", "valor1"], ["clave2", "valor2"]];

// El constructor por defecto de Map para transforar un Array 2D (clave-valor) en un mapa
var miMapa = new Map(kvArray);

miMapa.get("clave1"); // devuelve "valor1"

// Usando la función Array.from para transformar el mapa a un Array 2D clave-valor.
console.log(Array.from(miMapa)); // Muestra exactamente el mismo Array que kvArray

// O usando los iteradores de claves o valores y convirtiendo a array.
console.log(Array.from(miMapa.keys())); // Muestra ["clave1", "clave2"]