/* 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];
// Use map to create a new array in memory. Don't use if you're not returningconst arr =[1,2,3,4]// Get squares of each elementconst sqrs = arr.map((num)=> num **2)console.log(sqrs)// [ 1, 4, 9, 16 ]//Original array untouchedconsole.log(arr)// [ 1, 2, 3, 4 ]
// Map objects are collections of key-value pairs. // A key in the Map may only occur once, it is unique in the Map 's collectionlet map =newMap()let keyArray ='Array'
map.set(keyArray,[1,2,3,4,5])
map.get(keyArray)// 1, 2, 3, 4, 5
// make new array from edited items of another arrayvar newArray = unchangedArray.map(function(item, index){return item;// do something to returned item});// same in ES6 style (IE not supported)var newArray2 = unchangedArray.map((item, index)=> item);
//map() methods returns a new arrayconst data ={name:"laptop",brands:["dell","acer","asus"]}let inside_data = data.brands.map((i)=>{console.log(i);//dell acer asus});
//map is higher order function const names=["Shirshak","SabTech","Fiverr"]const newNames= names.map(function(name){console.log(video)})console.log(newVideos)//(3) [undefined, undefined, undefined]//map always try to return somethings if we don't return we get undefined.//map is used for modification,copy of array.//copy of array using mapconst newNames= names.map(function(name){return name;})
let myMap =newMap()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"
var miMapa =newMap();var claveObj ={},claveFunc=function(){},
claveCadena ="una cadena";// asignando valores
miMapa.set(claveCadena,"valor asociado con 'una cadena'");
miMapa.set(claveObj,"valor asociado con claveObj");
miMapa.set(claveFunc,"valor asociado with claveFunc");
miMapa.size;// 3// obteniendo los valores
miMapa.get(claveCadena);// "valor asociado con 'una cadena'"
miMapa.get(claveObj);// "valor asociado con claveObj"
miMapa.get(claveFunc);// "valor asociado con claveFunc"
miMapa.get("una cadena");// ""valor asociado con 'una cadena'"// porque claveCadena === 'una cadena'
miMapa.get({});// undefined, porque claveObj !== {}
miMapa.get(function(){})// undefined, porque claveFunc !== function () {}var myMap =newMap();
myMap.set("bar","foo");
myMap.delete("bar");// Retorna true. Eliminado con éxito.
myMap.has("bar");// Retorna false. El elemento "bar" ya no está presente.
var array ="M 175 0 L 326.55444566227675 87.50000000000001 L 326.55444566227675 262.5 L 175 350 L 23.445554337723223 262.5 L 23.44555433772325 87.49999999999999 L 175 0".split(" ");let neWd = array.map(x=>{if(x ==='M'|| x ==='L'){return x;}else{return x *2;}}).join(' ')console.log(neWd);
var kvArray =[["clave1","valor1"],["clave2","valor2"]];// El constructor por defecto de Map para transforar un Array 2D (clave-valor) en un mapavar miMapa =newMap(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"]
functionsquare(arr){const newArr = arr.map(x=> x * x );return newArr ;//if you find this answer is useful ,//upvote ⇑⇑ , so can the others benefit also . @mohammad alshraideh ( ͡~ ͜ʖ ͡°)
//forEach vs. Map High Order Array Methodsconst arr =[1,2,3]const arr2 =[...arr,4,5]//see spread operator grepper answer for [...arr]//the forEach doesn't return anything, it just loops through the array
arr2.forEach(function(item){console.log(item +' of '+ arr2.length)})//map allows us to return an array and store it into a new arrayconst arr3 = arr2.map(function(item){//after performing some operation on all the objects of the array//we can then return all those values into a new arrayreturn item *2})console.log(arr3)
// use the map method on an array.// define arraylet scores =[10,25,30]// use of map, we store the map method in to a variable called doubledScorelet doubledScore = scores.map(function(score){return score *2// returns every value of the array * 2 })console.log(doubledScore)// [20, 50, 60]
const result =newMap();//create a new map
result.set('a',1);
result.set('b',2);console.log(result);const germany ={name:'Germany',population:8000000};//create a new object
result.set(germany,'80m');//set the object to the mapconsole.log(result);
result.delete('a');//delete the key 'a'console.log(result);
result.clear();//clear all the keys in the mapconsole.log(result);
# map function
city_lengths =map(len,['sanjose','cupertino','sunnyvale','fremont'])print(list(city_lengths))
# [7,9,9,7]
# Map takes a function and a collection of items.It makes a new, empty collection, runs the function on each item in the original collection and inserts each return value into the newcollection.It returns the newcollection.
const numbers =[2,7,9,171,52,33,14]consttoSquare=num=> num * num
constsquareNums=newNumbers=>
newNumbers.map(toSquare);console.log(squareNums(numbers));