0

I realize this is a somewhat off manner of operations, but for the sake of possibility, I'm wondering if anyone can help?

Here array2 is holding the end state I would like array1 to hold (only I want to do it with the for loop. It's fine that each sub_array's have to be initialized as their own variables, I'm just trying to get the array1 to hold N number of sub_arrays via the loop.

Here is the example I've tried, but trying to "compile" it via a string doesn't allow the sub_arrays to be called in a useable manner.

var numberOfSubArrays = 3
var sub_array1 = []
var sub_array2 = []
var sub_array3 = []

var array1 = []
var array2 = [sub_array1,sub_array2,sub_array3]

for (var i = 0; i < numberOfSubArrays; i++) {
    array1[i] = "sub_array" + i
}

Any thoughts would be much appreciated!

4
  • Do you mean array1[i] = array2[i]? Or perhaps some kind of concat? Commented Feb 7, 2016 at 6:55
  • Or for (var i = 0; i < numberOfSubArrays; i++) { eval("array1[" + i +"] = sub_array" + i); } Commented Feb 7, 2016 at 6:55
  • @mplungjan array2 is an array holding references of other arrays. If it was an object with keys sub_array1....n then we could do just like you advised. Am i right? Commented Feb 7, 2016 at 7:03
  • Early morning here.... Commented Feb 7, 2016 at 7:15

2 Answers 2

1

var numberOfSubArrays = 3
var sub_array1 = [1]
var sub_array2 = [2]
var sub_array3 = [3]

var array1 = []
// we don't need array2 at all
//var array2 = [sub_array1,sub_array2,sub_array3]

// you need to count from 1..n, as you named your sub_arrays like that
for (var i = 1; i <= numberOfSubArrays; i++) {
    // you can use eval, but be careful, eval is evil!
    array1[i-1] = eval("sub_array" + i)
}
console.log(array1);

Sign up to request clarification or add additional context in comments.

4 Comments

Yes! I just didn't know eval was a thing. Many thanks
Right, but I think the intention was not to have the array2 in the code :)
I think array2 was just to show us what they want in array1 -- as in references to the arrays, not just their names as strings.
BTW, see my answer for an eval-free and BPA-free alternative :)
1

Using eval is yucky. This will work in browsers:

var numberOfSubArrays = 3
var sub_array1 = []
var sub_array2 = []
var sub_array3 = []

var array1 = []
var array2 = [sub_array1,sub_array2,sub_array3]

for (var i = 0; i < numberOfSubArrays; i++) {
    array1[i] = window["sub_array" + i + 1];
}

In browsers, "global" vars are really objects in "window". Note: this will not work in tools like jsfiddle, because they put your code inside a function (that you don't see).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.