The concept behind the map()
function in Javascript is quite straightforward.
Imagine you have a dataset like this:
var dataSet = [{
humidity: 10.4,
temperature: 20.9,
},
{
humidity: 12.7,
temperature: 24.2,
}];
To begin with, the function will iterate through each entry in your dataset, giving it a time complexity of O(n)
. While this might not be a concern for personal projects or casual coding, it's something to keep in mind. The function then creates a new collection based on the operations performed on your dataset. If, for instance, you want to extract only the humidity values, you can simply do this:
var dataSet = ...; //Refer to above
var humidityCollection = dataSet.map(function(element) {
return element['humidity']; //Alternatively, element.humidity
});
For those using ECMAScript 6 and newer versions, you can streamline the process with a lambda expression. The functionality remains the same, but the code becomes more succinct and easier to comprehend.
var humidityCollection = dataSet.map((element) => {
return element['humidity'];
});
As a result, your dataset will look like this:
[10.4, 12.7]
For additional resources and detailed documentation, refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map