Transforming JavaScript Arrays using map()
Array.prototype.map() method creates and returns a new array with the results of calling a provided function on every element in the calling array.
We can use this method to transform or change elements of an array.
In the following example, we add number 10
to every number in the initial array nums
. The resultant array returned by map()
is stored in the variable newNums
. The original array isn’t modified.
Example
Output
Let us look at another example of using map()
on an array containing objects.
Example
Output
We can also use latest ES6 features and write the map()
method as:
Avoid mutating original array
When using map()
on an array of objects, be careful to avoid mutating (modifying) original array and make sure to return a new object from the callback function.
At first glance, the above code looks good. But we should observe that we are assigning an object reference to newProduct
, therefore modifying newProduct
also modifies the original object.
If we print productsInUSD
array elements to the console, we can see that they are modified and now contain prices in INR. This isn’t desired and breaks functionality in other parts of our application.
To avoid this, clone the object before assigning. There are several ways to clone an object, let us use JSON.parse(JSON.stringify(object))
for this example.
This doesn’t modify the original array and prevents any unintended effects.