0

Say that I have a for loop with index i, and I want to have a variable with a name that ends with the character(s) of the index number. Therefore, each time for loops, it will create a variable with a unique name. I want this variable to be a global variable, too. And then, I would want to use each of those variables later by calling var name(i) name of index. It would be okay if they were called some other way, too.

It could maybe be done with an array, but with this case, I end up with an array of arrays again, and I need a single array. I need to start with an array of arrays, too.

var arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
var array = [];
for(i = 0; i < arrays.length; i ++)
  array[i] = arrays[i];

And I cannot simply use the reduce function because I want each of the arrays in my array of arrays to be a separate array.

var arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
  arrays.reduce(function(a, b){
    return a.concat(b);
  }, []);

Note that the input array of arrays will be different each time the program runs and sometimes be jagged.

JavaScriptArray
  • 140
  • 2
  • 11
  • You can use `Array.prototype.concat.apply([], arrays)` to merge it into one array. (This is probably the easiest to me). – soktinpk Aug 25 '14 at 22:30

2 Answers2

1

I'm not sure I understand your question. You can create variables in the global scope using the syntax window[varname]

So if you want a seperate variable for each array in arrays, you could do this:

var arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
for(i = 0; i < arrays.length; i++)
    window["array"+i] = arrays[i];

You could then access the arrays as array0, array1, etc.

Edit: fiddle: http://jsfiddle.net/5exfwne1/

SimpleJ
  • 13,812
  • 13
  • 53
  • 93
  • Wow! That's cool!! :) Is there a way to find how many array0, array1, array2, etc. there are without having to go back to the original array of arrays? If not, I have what I need. Thanks so much!!! :) – JavaScriptArray Aug 25 '14 at 22:40
  • I know that if I went back to the original array of arrays I could use arrays.length – JavaScriptArray Aug 25 '14 at 22:40
0

I noticed varios syntax errors in your second declaration, however, it looks like what you intend to do is:

var arrays= [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

  arrays.reduce(function(a, b){
    a = a.concat(b); return a;
  },[]); //outputs [1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.prototype.reduce needs to be initialized as an array by arrays.reduce(function(a, b){},[]) the [] initialize it as array instead of 0. This function also needs to return something, in this case the concatenated array.

Dalorzo
  • 19,834
  • 7
  • 55
  • 102