Sid Sid - 9 months ago 35
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.


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 = {
  var filter = arr2.filter(function(y) {
    return y[0] == x;
  }).map(function(y) {
    return y[1];
  return [x, filter];