0

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?

3
  • 1
    1) Is it about Java or JavaScript? 2) You know how to accept answers? Commented May 18, 2012 at 17:23
  • 1
    Seems Javascript, as I never saw var in Java. Commented May 18, 2012 at 17:24
  • It is in javascript only not in java Commented May 18, 2012 at 17:27

3 Answers 3

1

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.

http://jsfiddle.net/P9SSA/1/

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

Comments

1

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"];

forEach shim
map shim

3 Comments

Why not use for(var i = ...)? Hint: MSIE.
@SalmanA because it allows the answer to be more meat and less boilerplate.
@Esailija Thanks for your reply. i had tried with your approach it doesn't worked for me. can you provide some more code
0
var arrayOfArrays = [];
for (var i = 0; i < arr.length; i++) {
    arrayOfArrays[i] = [];
    arrayOfArrays[i].push(arr[i]); 
}

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.