d3.js: how to use map function?

后端 未结 2 1047
太阳男子
太阳男子 2021-02-19 10:36

How can I use d3.map() to get [10, 12] out of the following array?

var mydata = [ 
  { \'__data__\' : 10 }, 
  {\'__data__\' : 12 }
];          


        
相关标签:
2条回答
  • 2021-02-19 11:08

    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.

    0 讨论(0)
  • 2021-02-19 11:14

    .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);
    
    0 讨论(0)
提交回复
热议问题