Sid Sid - 5 months ago 18
Javascript Question

Merge two arrays by grouping based on elements of 1st array in Javascript

I have two arrays (arr1 & arr2) like this

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

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


I want to group them together into 3rd array in javascript based on the values of first array. Desired Output:

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


NOTE: I had arr2 to begin with and was able to retrieve first value and remove duplicates into arr1.

Please advise.

Answer

Try like this

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