How do I access the array sum here?

后端 未结 2 1362
-上瘾入骨i
-上瘾入骨i 2021-01-21 00:37

I have a data set that looks roughly like this:

var dataset = [
  // apples
  [{\"x\": 1, \"y\": 5 }, { \"x\": 2, \"y\": 4 }, { \"x\": 3, \"y\": 2 }, { \"x\": 4,         


        
相关标签:
2条回答
  • 2021-01-21 00:55

    d3.zip() comes in handy here, since you're manipulating data based on array index.

    https://jsfiddle.net/guanzo/o8voyydx/2/

    var result = dataset.map(d=>d.map(d=>d.y))
    result = d3.zip.apply(undefined,result)
    result = d3.max(result.map(d=>d3.sum(d)))
    console.log(result )//83
    
    0 讨论(0)
  • 2021-01-21 01:01

    Here's a horrifying solution and as close to a "one-liner" as I can get. It'll handle un-even length arrays too:

    <!DOCTYPE html>
    <html>
    
    <head>
      <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
    </head>
    
    <body>
      <script>
        var dataset = [
          // apples
          [{
            "x": 1,
            "y": 5
          }, {
            "x": 2,
            "y": 4
          }, {
            "x": 3,
            "y": 2
          }, {
            "x": 4,
            "y": 7
          }, {
            "x": 5,
            "y": 23
          }],
          // oranges
          [{
            "x": 1,
            "y": 10
          }, {
            "x": 2,
            "y": 12
          }, {
            "x": 3,
            "y": 19
          }, {
            "x": 4,
            "y": 23
          }, {
            "x": 5,
            "y": 17
          }],
          // grapes
          [{
            "x": 1,
            "y": 22
          }, {
            "x": 2,
            "y": 28
          }, {
            "x": 3,
            "y": 32
          }, {
            "x": 4,
            "y": 35
          }, {
            "x": 5,
            "y": 43
          }]
        ];
      
       var l = d3.max(dataset, function(d){
         return d.length;
       }), 
       sumArr = d3.range(l).map(function(i){
         return dataset.map(function(d){
           return d[i] ? d[i].y : 0;
         });
       }).map(function(d){
         return d3.sum(d);
       });
       
      d3.select("body").text(sumArr);
        
      </script>
    </body>
    
    </html>


    P.S. Eric's solution is so much better...

    0 讨论(0)
提交回复
热议问题