Mapping
The Map Function and How to Use It
This is just a post about one a useful, versatile function known as the Map function. As everyone knows, there are often many ways to accomplish the same coding task. Hopefully this article can serve as an intro to Mapping in JavaScript, and show when to use it, or use something else.
In JavaScript, the map function will go something like this:
newArray = oldArray.map(value => {
value * x
})
Basically you apply an action to each index of the array to produce a new array. This array could have the same value, if you need to map over the array without changing it. The callback function could also be written more simply, such as this example:
newArray = oldArray.map(value => value + 1).
In this case, the new array will have values that are one more than the other array. Map functions can also accomplish much more complex operations involving multiple variables.
Here's a less useful example:
let total = 0
newArray = oldArray.map(value => {
total = total + value;
return value
})
In this example, the array remains unchanged, but each value of the array is still iterated over, and a sum of all the numbers is collected. A better way to do this might be to use a reduce function, but this just shows how map can do everything. The main advantages the map function has over simply iterating over lists with a loop is direct access to each value of the array and the ability to create new arrays with one command. The above example uses neither of these advantages well. It doesn't change the value, and it creates a new array that's exactly the same as the old array.
Mapping can be quite useful when creating several arrays from one, like this:
array1 = [
{name: "Bob", age: 54, occupation "Programmer"},
{name: "Lisa", age: 25, occupation "Musician"},
{name: "Kevin", age: 38, occupation "Construction"}
]
let ages = array1.map(item => item.age)
let nameOccupations = array1.map(item => {
return {name: item.name, occupation: item.occupation}
})
This example just created 2 arrays, one of objects, and one of integers, from a single array of objects.
Whether it's for iterating and operating on each value of the array, or creating multiple arrays from objects, map can be very useful in JavaScript. It might be less useful when you're simply iterating or using outside variables.