Reputation: 255
I have one array in javascript like
var arr = ["aa","bb","cc", "dd"];
and now I want to store these values into multiple arrays dynamically like
var arr1 = ["aa"];
var arr2 = ["bb"];
var arr3 = ["cc"];
var arr4 = ["dd"];
Here the as per the size of the "arr" array I need to create dynamic arrays to store those values. For example in "arr" I have 4 values then I need to create 4 dynamic arrays to store 4 values.
I dont have any idea how to achieve this any help?
Upvotes: 0
Views: 1014
Reputation: 140210
In global scope you can do:
arr.forEach( function( value, index ) {
window["arr"+(index+1)] = [value];
});
Inside arbitrary scope, this is only possible under non-strict eval:
var arr = ["aa","bb","cc", "dd"];
eval( arr.map( function( value,index) {
value = typeof value == "string" ? '"' + value + '"' : value;
return 'var arr'+(index+1)+' = ['+value+']';
}).join(";") + ";" );
Evaluates the following code:
var arr1 = ["aa"];
var arr2 = ["bb"];
var arr3 = ["cc"];
var arr4 = ["dd"];
Upvotes: 1
Reputation: 6057
The only way I can think of doing exactly what you are asking for is with eval. I don't suggest using it so I put together an object, which is close and preferred.
var myOneArray = ["a","b","c","d"];
var varPrefix = "arr";
var myObj = {};
for (var i = 1; i <= myOneArray.length; i++) {
eval(varPrefix + i + '=["' + myOneArray[i-1] + '"]');
myObj[varPrefix + i] = [myOneArray[i-1]];
}
document.write(arr1);
document.write("<br>");
document.write(myObj.arr3);
Upvotes: 1
Reputation: 691645
var arrayOfArrays = [];
for (var i = 0; i < arr.length; i++) {
arrayOfArrays[i] = [];
arrayOfArrays[i].push(arr[i]);
}
Upvotes: 0