Map is the method that helped open up data manipulation on the front end for me. It is a powerful tool to know and in the blog post I'll try to shed some light on how to use the array Map function.
const fakeData = [1,2,3,4]; const mappedData = fakeData.map((data) => { return {key: data}; }); console.log(mappedData); // output : [{key: 1, },{key: 2}, {key: 3}, {key: 4 }]
Console:
In this example, we start with an array of numbers. Now we can run map on the array (any array has access to the map method).
Map iterates over each item in the array it is called on. We pass in a callback function to map, this callback gets executed on each item in the index. And the return value of the callback is added to a new copy of the array.
const fakeData = [1,2,3,4]; const mappedData = fakeData.map((data) => { return data * 2; }); console.log(mappedData); // output : [2, 4, 6, 8]
Console:
In this example you can see that the callback multiplies the initial data value by 2. Resulting in a new array with the same length as the original but all the values double.
One important thing to remember is that map always returns a new array and does not mutate the original array.
Now get out there and start mapping data