簡體   English   中英

根據另一個等長數組中的值拆分數組-Javascript

[英]Split array based on values in another array of equal length - 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中該索引處的項目。

我想基於inputLabels中的標簽(A,B和C)將inputValues拆分為一個新的數組數組,同時還要創建一個唯一標簽值的新數組,以便獲得:

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中的正確子數組。

理想情況下,解決方案將是通用的,以便inputLabel可以具有三個以上的唯一值(例如“ A”,“ B”,“ C”,“ D”,“ E”),因此可以在splitValues中產生三個以上的子數組。

 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" ],
    // ...
}

我認為這比您期望的結果更有條理。

使用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)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM