-3

Let's say I have three Arrays and I want to essentially merge them into one super array in Javascript. I don't necessarily know their lengths and if all three arrays would be set. This is essentially for a filtering system.

So there is a Category Array, an Author Array, and a Type Array. They all store unique keys.

So... Category Might be [Cat1,Cat2]
Author Might be [Author7,Author8]
Type Might be [Type9,Type11]

This will make another array with these values

[
     Cat1 Author7 Type9,
     Cat1 Author7 Type11,
     Cat1 Author8 Type9, 
     Cat1 Author8 Type 11,
     Cat2 Author7 Type9,
     Cat2 Author7 Type11,
     Cat2 Author8 Type9, 
     Cat2 Author8 Type 11,
]

So its sort of like possible combinations from the arrays. Sometimes one or two of the arrays might be empty. I can create a bunch of if statements but there has to be a better way.

Thanks much.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252

1 Answers1

0

You just need 3 nested foreach() loop :

var cat = ["Cat1","Cat2"];
var author = ["Author7","Author8"];
var type = ["Type9","Type11"];
var result = []

cat.forEach(x => author.forEach(y => type.forEach(z => result.push(x.concat(y).concat(z)))));
console.log(result);
If type is empty :

var cat = ["Cat1","Cat2"];
var author = ["Author7","Author8"];
var type = [];
var result = []

cat.forEach(x => author.forEach(y => type.length === 0 ? result.push(x.concat(y)) : type.forEach(z => result.push(x.concat(y).concat(z)))));
console.log(result);
kevin ternet
  • 4,514
  • 2
  • 19
  • 27