2016-04-10 73 views
-1

得到這個數組:彙總數組值,強調

var arr = [ 
     { 
     series: [ 
      { 
      "name": 2014, 
      "data": [19, 17, 15, 12, 10, 10, 12, 10, 11, 14, 14, 18] 
      }, 
      { 
      "name": 2015, 
      "data": [18, 17, 16, 12, 10, 7, 6, 8, 8, 11, 15, 30] 
      }, 
     ] 
     }, 
     { 
     series: [ 
      { 
      "name": 2014, 
      "data": [32, 17, 15, 12, 33 10, 33, 10, 11, 14, 14, 18] 
      }, 
      { 
      "name": 2015, 
      "data": [45, 10, 12, 55, 77, 7, 6, 8, 8, 11, 33, 30] 
      }, 
     ] 
     }, 
    ] 

我需要創建一個返回summrized系列的功能:

var series = [ 
    { 
    year: '2014', 
    data: [51, 34....], 
    }, 
    { 
    year: '2015', 
    data: [63, 27....], 
    } 
] 

我所能,循環做到這一點,但我想有一些聰明的做法與下劃線?可能與reduce功能。任何想法如何做到這一點?

回答

1
var arr = [{  
    "series": [{  
     "name": 2014,  
     "data": [19, 17, 15, 12, 10, 10, 12, 10, 11, 14, 14, 18]  
    }, {  
     "name": 2015,  
     "data": [18, 17, 16, 12, 10, 7, 6, 8, 8, 11, 15, 30]  
    }]  
}, {  
    "series": [{  
     "name": 2014,  
     "data": [19, 17, 15, 12, 10, 10, 12, 10, 11, 14, 14, 18]  
    }, {  
     "name": 2015,  
     "data": [18, 17, 16, 12, 10, 7, 6, 8, 8, 11, 15, 30]  
    }]  
}];  


_.chain(arr)  
    .map('series')  
    .flatten()  
    .reduce(function(object, value) {  
     object[value.name] = !object[value.name] ? value.data : _.union(object[value.data], value.data);  
     return object;  
    }, {})  
    .reduce(function(arr, value, key) {  
     arr.push({  
      year: key,  
      data: value  
     });  
     return arr;  
    }, [])  
    .value();  
0

您可以使用一些迭代和對象作爲年份的參考進行分組。

var arr = [{ series: [{ "name": 2014, "data": [19, 17, 15, 12, 10, 10, 12, 10, 11, 14, 14, 18] }, { "name": 2015, "data": [18, 17, 16, 12, 10, 7, 6, 8, 8, 11, 15, 30] }] }, { series: [{ "name": 2014, "data": [32, 17, 15, 12, 33, 10, 33, 10, 11, 14, 14, 18] }, { "name": 2015, "data": [45, 10, 12, 55, 77, 7, 6, 8, 8, 11, 33, 30] }] }], 
 
    series = []; 
 
    
 
arr.forEach(function (a) { 
 
    Object.keys(a).forEach(function (k) { 
 
     a[k].forEach(function (b) { 
 
      if (!this[b.name]) { 
 
       this[b.name] = { year: b.name, data: [] }; 
 
       series.push(this[b.name]); 
 
      } 
 
      b.data.forEach(function (c, i) { 
 
       this[b.name].data[i] = (this[b.name].data[i] || 0) + c; 
 
      }, this); 
 
     }, this); 
 
    }, this); 
 
}, {}); 
 
    
 
document.write('<pre>' + JSON.stringify(series, 0, 4) + '</pre>');