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.

2
  • What do you mean by print? To the console window? To HTML? Commented Aug 18, 2015 at 1: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. Commented Aug 18, 2015 at 15:31

1 Answer 1

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('-----------------');
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.