How can I use d3.map()
to get [10, 12]
out of the following array?
var mydata = [
{ '__data__' : 10 },
{'__data__' : 12 }
];
I have been trying this, but it doesn't work:
var mymap = d3.map(mydata, function(d) {
return d.__data__;
});
You can't -- d3.map()
isn't for mapping a function across an array, but a shim for hashes. Briefly, while objects can be used like hashes, there are situations when unexpected behaviour can occur. A new Javascript standard proposes a solution to this, and until it is implemented, d3.map()
can be used to the same effect.
More information in the documentation .
.map() just creates another array, having traversed whatever you gave it and performing a function you defined on each element in the old array and then that becomes the new array.
so if i wanted to perform a single operation on all elements in an array and make a new array out of it, i'd use .map()
for example, i need to see something represented as percentages when the data i'm getting from /proc/loadavg gives me numbers like 0.28, 0.03, 1.0, 0.97, 0.04, etc for every 5-15 min load avg. but i also need the output from running nproc in my calculation, and nproc gives me how many cores over which things are distributed. so i create an array each time /proc/loadavg gives me a new value, and i push each new value onto an array...
This would be your initial data:
var data = [0.28,0.03,1.0,0.97,0.04];
var dataSize = 5;
This could be the function to use to apply to all indexes in your original data array:
percent = function () {
return (loadval/(numCores*100));
}
This would be mapping it to a new array with the transformed values:
data = d3.range(dataSize).map(percent);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.