0

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Rather than creating arr1 as a middle step, I would probably create an object as the middle step:

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"]}

To convert that object to your desired output array:

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

If you actually need the arr1 array for something else then:

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

But notice that obj is quite useful for further processing, because if you need to get the values associated with "B" you don't need to search through an array again, you can simply say obj["B"] (which will give the array ["ba","bb","bc"]). So the second "B" value is obj["B"][1].

Further reading:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.