mapping in js code example

Example 1: javascript map

array.map((item) => {
  return item * 2
} // an example that will map through a a list of items and return a new array with the item multiplied by 2

Example 2: maps in javascript

// Map decalaration in javaScript
const obj1 = { name: 'ismail' };
const obj2 = { name: 'sulman' };
const obj3 = { name: 'naeem' };

firstMap = new Map([
    [
        [obj1, [{ date: 'yesterday', price: '10$' }]], // using object as a key in the map and object inside the array
        [obj2, [{ date: 'today', price: '100$' }]]
    ]
]);
firstMap.set(obj3, [{ date: "yesterday", price: '150$' }]); //pushing the obj to the Map

// iterating the Map
for (const entry of firstMap.entries()) {
    console.log(entry);
};

console.log(firstMap);

firstMap.delete(obj3);
console.log(firstMap);

Example 3: javascript map

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

function listFruits() {
  let fruits = ["apple", "cherry", "pear"]
  
  fruits.map((fruit, index) => {
    console.log(index, fruit)
  })
}

listFruits()

// https://jsfiddle.net/tmoreland/16qfpkgb/3/

Example 5: 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 6: 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 ]

Tags:

Misc Example