The map() function; creating new arrays in JavaScript and its importance in React
Map() is a valuable function featured in the JavaScript library, which allows one to quickly create new arrays from existing arrays. This is helpful in solving algorithms, and pulling out and displaying data, especially in React.
Here’s a simple algorithm problem: given an array of numbers, create a new array multiplying each number by 2:
let array = [41,42,43,44,45,46,47,48,49];let mapArray = array.map(number => number * 2);console.log(mapArray);
// [82, 84, 86, 88, 90, 92, 94, 96, 98]
Using ES6 syntax, the map()
function takes the value of each element, assigns it as the variable number
, multiplies that number
by 2
, and adds that value into the new declared mapArray
.
Because JavaScript is a mid-level language, we could do this in a more traditional way, using a for
loop, but it is much harder (or easier) to read:
let array = [1,2,3,4,5];let mapArray = [];for(let i=0; i<array.length; i++){
let value = array[i]*2;
mapArray.push(value);
}console.log(mapArray);
//[ 2, 4, 6, 8, 10 ]