0

If I have multiple arrays (I dont know how many, or their length)

arr1 = ["a","b","c"];
arr2 = ["red","green"];
arr3 = ["10","11","12","13"];

And I would like to have something like

res = [ 
          ["a","red","10"], ["a","red","11"],
          ["a","red","12"],["a","red","13"],
          ["a","green","10"],["a","green","11"], 
          ...   
     ]; 

You know, combine them... I dont know the number of arrays or the length.. And the final result be One array with all possible combinations.

9
  • Will they all have the same length? Commented Apr 18, 2016 at 20:08
  • If you want a multidimensional array just create a new array and push each sub array into it. var arr = []; arr.push(arr1); arr.push(arr2); etc. If you can do this programmatically depends on how you get your arrays in the first place. Commented Apr 18, 2016 at 20:10
  • 1
    This looks a bit more complicated than those suggestions, he needs every combination of every array element. Commented Apr 18, 2016 at 20:11
  • Every array content is a Kind of information the User gave me. So I really dont know how many "type" of content he will give. Also how many itens in each content.. So they will not be the same length.. And They will not be 3 arrays.. they can be many arrays.. maybe 50 arrays.. maybe not.. Commented Apr 18, 2016 at 20:12
  • @IrkenInvader Good point i missed that in his example data. Commented Apr 18, 2016 at 20:12

1 Answer 1

-2

You should be able to use the array method reduce to create a single array.

/** @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Examples */

var arr1 = ["a", "b", "c"],
  arr2 = ["red", "green"],
  arr3 = ["10", "11", "12", "13"],
  flattened = [arr1, arr2, arr3].reduce(function(a, b) {
    return a.concat(b);
  }, []);

alert(flattened);

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.