0
[['red','yellow'],['xl','xxl']]

above is an array of variant of clothes, how to print 4 set of combination below:

red xl, red xxl, yellow xl and yellow xxl

It seems easy but because it might be more data like another array (or more), I can't do data[0] or data[1] in this case.

Alice Xu
  • 533
  • 6
  • 20
  • What do you mean by print? To the console window? To HTML? – Mike Aug 18 '15 at 01:58
  • I've added an answer that does not require the underscore library and should be easy to read... just in case you still need it. – GPicazo Aug 18 '15 at 15:31

1 Answers1

0

This should work:

// data to process and print
var data = [['red','yellow'],['xl','xxl'], ['boy', 'girl']];

var combinations = [], // will hold the running processed strings as we iterate
    temp = [], // temporary array
    isFirstPropSet = true; // flag to determine if we are processing the first property set (colors in this case)

// for each property set
data.forEach(function(datum) {
  // if it isn't the first property set, make a copy into temp and reset our combinations array
  if (!isFirstPropSet) {
    temp = combinations.splice(0);
    combinations = [];
  }

  // for each property in the current property set
  datum.forEach(function(prop) {
    // if it is the first property set, simply add it to the current running list
    if (isFirstPropSet) {
      combinations.push(prop);
    } else {
      // otherwise for each of the previous items, lets append the new property
      temp.forEach(function(comb) {
        combinations.push(comb + ' ' + prop);
      });
    }
  });

  // make sure to unset our flag after processing the first property set
  isFirstPropSet = false;
});

// print out all the combinations
combinations.forEach(function(comb) {
  console.log(comb);
});

console.log('-----------------');
GPicazo
  • 6,516
  • 3
  • 21
  • 24