2

I'm looking for a way to generate all possible combinations from several arrays. When it comes to 1, I was able to find solutions, however when it comes to more, then it gets problematic. To understand my issue easier, let's say we have this two arrays:['small','big'] and ['red', 'green'], and the result I'm trying to get is:

small green ball, small red ball, big green ball, big red ball, green ball, red ball, small ball, large ball, green small ball, red large ball and etc.

The biggest difficulty for me is to figure out how you would make it so that, there wouldn't be any repeats from each array, example : small large ball or green red ball.

Combustible Pizza
  • 315
  • 1
  • 2
  • 8
  • Do you just need the cartesian product of the items, or are you looking for all possible combinations no matter if they repeat (in content, but not order)? – wiesion Jun 01 '18 at 13:14

2 Answers2

1

Here is my solution

let sizes = ['small', 'medium sized', 'big']
let colors = ['green', 'red', 'blue']
let objects = ['ball', 'square']

const flatten = list => list.reduce(
   (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
);

function uniqeCombine(...data) {
  
  const flat = flatten(data);
  return flat.reduce( (acc, v, i) =>
    acc.concat(flat.slice(i+1).map( w => v + ' ' + w )),
  []);
}


console.log(uniqeCombine(sizes, colors, objects))
ArtemSky
  • 1,173
  • 11
  • 20
0

Use nested for loops. With for of you can easy loop through each object in the array:

let sizes = ['small', 'medium sized', 'big']
let colors = ['green', 'red', 'blue']
let objects = ['ball', 'square']

for (size of sizes) {
  for (color of colors) {
    for (object of objects) {
      console.log(size, color, object)
    }
  }
}

To get the green big ball and big green ball:

const sizes = ['small', 'big']
const colors = ['green', 'red']

for (let size of sizes) {
  for (let color of colors) {
    console.log(size, color, 'ball')
  }
}
for (let color of colors) {
  for (let size of sizes) {
    console.log(color, size, 'ball')
  }
}
marcel.js
  • 313
  • 2
  • 12
  • While this mostly works, however in the result example, I showed that the elements from both arrays can be at any position, like : **large green ball** or **green large ball** – Combustible Pizza Jun 01 '18 at 13:08
  • I've added a code snipped which should do what you're looking for. – marcel.js Jun 01 '18 at 13:20