use map in 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
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 3: 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 4: 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 5: 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 6: map in javascript
['elem', 'another', 'name'].map((value, index, originalArray) => {
console.log(.....)
});