xxxxxxxxxx
.map() is a JavaScript array method that creates a new array with the results of calling a provided function on every element in the calling array. It does not modify the original array. Here's an example:
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
In this example, the .map() method is used to double each element in the numbers array and returns a new doubledNumbers array with the results.
xxxxxxxxxx
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]
xxxxxxxxxx
let numbers = [1, 2, 3, 4, 5];
let doubles = numbers.map(number => number * 2)
console.log(doubles)
// --> [ 2, 4, 6, 8, 10 ]
xxxxxxxxxx
const people = [
{ firstName: 'Brian', lastName: 'Troncone' },
{ firstName: 'Todd', lastName: 'Motto' }
];
const peopleWithFullName = people.map(person => ({
person,
fullName: `${person.firstName} ${person.lastName}`
}));
// [{ firstName: 'Brian', lastName: 'Troncone', fullName: 'Brian Troncone' }, {firstName: 'Todd', lastName: 'Motto', fullName: 'Todd Motto' }]
console.log(peopleWithFullName);
--
const people = [
{ firstName: 'Brian', lastName: 'Troncone' },
{ firstName: 'Todd', lastName: 'Motto' }
];
const lastNames = people.map(person => person.lastName);
// [ 'Troncone', 'Motto' ]
console.log(lastNames);
xxxxxxxxxx
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2;
}
xxxxxxxxxx
let arr = [1,2,3]
/*
map accepts a callback function, and each value of arr is passed to the
callback function. You define the callback function as you would a regular
function, you're just doing it inside the map function
map applies the code in the callback function to each value of arr,
and creates a new array based on your callback functions return values
*/
let mappedArr = arr.map(function(value){
return value + 1
})
// mappedArr is:
> [2,3,4]
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
xxxxxxxxxx
// the array: arr = [1,2,3]
arr.map( item(value), index(where in the array), array(The array on which they run));
xxxxxxxxxx
const shoppingList = ['Oranges', 'Cassava', 'Garri', 'Ewa', 'Dodo', 'Books']
export default function List() {
return (
<>
{shoppingList.map((item, index) => {
return (
<ol>
<li key={index}>{item}</li>
</ol>
)
})}
</>
)
}
Using map to reformat objects in an array
xxxxxxxxxx
const kvArray = [
{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 },
];
const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value }));
console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }]
console.log(kvArray);
// [
// { key: 1, value: 10 },
// { key: 2, value: 20 },
// { key: 3, value: 30 }
// ]