【问题标题】:Split array based on values in another array of equal length - Javascript根据另一个等长数组中的值拆分数组 - Javascript
【发布时间】:2017-09-17 18:15:30
【问题描述】:

我有两个长度相等的 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 中正确的子数组。

理想情况下,解决方案应该是通用的,这样 inputLabels 可以具有三个以上的唯一值(例如“A”、“B”、“C”、“D”、“E”),因此可以产生三个以上的子数组在 splitValues 中。

【问题讨论】:

    标签: javascript arrays sub-array


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      我认为这比你想要的结果更有条理。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-07
        • 2021-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多