xxxxxxxxxx
//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 map
const newNames= names.map(function(name){
return name;
})
xxxxxxxxxx
const products = [
{ name: 'Laptop', price: 32000, brand: 'Lenovo', color: 'Silver' },
{ name: 'Phone', price: 700, brand: 'Iphone', color: 'Golden' },
{ name: 'Watch', price: 3000, brand: 'Casio', color: 'Yellow' },
{ name: 'Aunglass', price: 300, brand: 'Ribon', color: 'Blue' },
{ name: 'Camera', price: 9000, brand: 'Lenovo', color: 'Gray' },
];
const productName = products.map(product => product.name);
console.log(productName);
//Expected output:[ 'Laptop', 'Phone', 'Watch', 'Aunglass', 'Camera' ]
xxxxxxxxxx
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
xxxxxxxxxx
const numbers = [1, 2, 3, 4, 5];
const bigNumbers = numbers.map(number => {
return number * 10;
});
xxxxxxxxxx
const numbers = [1, 4, 9];
const roots = numbers.map((num) => Math.sqrt(num));
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
xxxxxxxxxx
const numbers = [0,1,2,3];
console.log(numbers.map((number) => {
return number;
}));
xxxxxxxxxx
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]
xxxxxxxxxx
// make new array from edited items of another array
var 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);
xxxxxxxxxx
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const anotherItems = items.map(item => item * 2);
console.log(anotherItems);
xxxxxxxxxx
const numbers = [2, 4, 6, 8];
const result = numbers.map(a => a * 2);
console.log(result);
//Output: [ 4, 8, 12, 16 ]
xxxxxxxxxx
//forEach vs. Map High Order Array Methods
const 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 array
const 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 array
return item * 2
})
console.log(arr3)