2017-04-20 106 views
0

我具有相等長度的具有以下結構的兩個JavaScript數組:在長度相等的另一陣列基於值拆分陣列 - 的Javascript

var inputLabels = ["A", "A", "A", "B", "A", "A", "A", "B", "B", "B", "C"]; 
var inputValues = [5, 4, 6, 0.01, 7, 12, 2, 0.06, 0.02, 0.01, 98.7]; 

在inputValues的項目對應於該項目中inputLabels該索引處。

欲inputValues分成基於在inputLabels標籤(A,B & C)陣列的新的數組,同時也創造獨特的標籤值的新的數組,從而獲得:

var splitLabels = ["A", "B", "C"]; 
var splitData = [ 
       [5, 4, 6, 7, 12, 2], 
       [0.01, 0.06, 0.02, 0.01], 
       [98.7] 
       ]; 

其中splitLabels中每個項目的索引對應於splitValues中的正確子數組。

理想情況下,解決方案將是通用的,這樣inputLabels可以具有多於三個唯一值(例如「A」,「B」,「C」,「D」,「E」),因此可以產生三個以上splitValues中的子數組。

+3

你嘗試過這麼遠嗎? – evvels1

回答

0

function groupData(labels, values) { 
 
    return labels.reduce(function(hash, lab, i) { // for each label lab 
 
    if(hash[lab])        // if there is an array for the values of this label 
 
     hash[lab].push(values[i]);    // push the according value into that array 
 
    else          // if there isn't an array for it 
 
     hash[lab] = [ values[i] ];    // then create one that initially contains the according value 
 
    return hash; 
 
    }, {}); 
 
} 
 

 
var inputLabels = ["A", "A", "A", "B", "A", "A", "A", "B", "B", "B", "C"]; 
 
var inputValues = [5, 4, 6, 0.01, 7, 12, 2, 0.06, 0.02, 0.01, 98.7]; 
 

 
console.log(groupData(inputLabels, inputValues));

功能groupData此格式返回一個對象:

{ 
    "Label1": [ values of "Label1" ], 
    "Label2": [ values of "Label2" ], 
    // ... 
} 

我想這是很多組織的比你想要的結果。

0

可能的解決方案使用Array#map

var inputLabels = ["A", "A", "A", "B", "A", "A", "A", "B", "B", "B", "C"], 
 
    inputValues = [5, 4, 6, 0.01, 7, 12, 2, 0.06, 0.02, 0.01, 98.7], 
 
    hash = [...new Set(inputLabels)], 
 
    res = hash.map(v => inputLabels.map((c,i) => c == v ? inputValues[i] : null).filter(z => z)); 
 
    
 
    console.log(JSON.stringify(hash), JSON.stringify(res));