通过在Javascript中基于第一个数组的元素进行分组来合并两个数组

时间:2016-06-12 03:20:27

标签: javascript arrays

我有两个这样的阵列(arr1和arr2)

var arr1 = ["A","B","C"];

var arr2 = [["A","aa"], ["A","ab"], ["A","ac"],["B","ba"],["B","bb"],["B","bc"],["C","ca"],["C","cb"]];

我想根据第一个数组的值将它们组合成javascript中的第3个数组。期望的输出:

arr3 = [ ["A",["aa","ab","ac"]], ["B",["ba","bb","bc"] ], ["C",["ca","cb"]] ]

注意:我开始使用arr2并且能够检索第一个值并将重复项删除到arr1中。

请告知。

2 个答案:

答案 0 :(得分:2)

试试这个

var arr1 = ["A", "B", "C"];

var arr2 = [
  ["A", "aa"],
  ["A", "ab"],
  ["A", "ac"],
  ["B", "ba"],
  ["B", "bb"],
  ["B", "bc"],
  ["C", "ca"],
  ["C", "cb"]
];
var newVal = arr1.map(function(x) {
  var filter = arr2.filter(function(y) {
    return y[0] == x;
  }).map(function(y) {
    return y[1];
  });
  return [x, filter];
})
console.log(newVal);

DEMO

答案 1 :(得分:1)

  

注意:我开始使用arr2并且能够检索第一个值并将重复项删除到arr1中。

我可能会创建一个对象作为中间步骤,而不是创建arr1作为中间步骤:

var obj = arr2.reduce(function(a,b){
  if (!a[b[0]]) a[b[0]] = [];
  a[b[0]].push(b[1]);
  return a;
},{});

// obj is now {"A":["aa","ab","ac"],"B":["ba","bb","bc"],"C":["ca","cb"]}

要将该对象转换为所需的输出数组:

var arr3 = Object.keys(obj).map(function(v) { return [v, obj[v]]; });
// [["A",["aa","ab","ac"]],["B",["ba","bb","bc"]],["C",["ca","cb"]]]

如果您确实需要arr1数组用于其他内容,那么:

var arr1 = Object.keys(obj);
// ["A", "B", "C"]

但请注意,obj对于进一步处理非常有用,因为如果您需要获取与"B"相关联的值,则无需再次搜索数组,您可以简单地说obj["B"](将给出数组["ba","bb","bc"])。因此,第二个"B"值为obj["B"][1]

进一步阅读: