简体   繁体   中英

How do I create new arrays from a parent array?

I have an array like the following:

var myArray = [1,2,3];

I want to extract the array values and transfer each one to its own array variable. The result would look like this:

arr1=[1]
arr2=[2]
arr3=[3]

I have tried using the following code, but am not getting the desired result.

 var myArray = [1,2,3]; var myarr1=[]; var myarr2=[]; var myarr3=[]; var result = myArray.map(function(current){ return myarr1.push(current); }); console.log(myarr1) 

How can I move each value to its own variable?

It would be best if you put those arrays in an object, use reduce to loop through the array and assign the values :

 const arr = [1, 2, 3]; const arrays = arr.reduce((acc, curr, ndx) => { acc['myArr' + (ndx+1)] = [curr]; return acc; }, {}); console.log(arrays); 

But if you ( not recommended ) really really need global variables, use the put them in the window object :

 const arr = [1, 2, 3]; arr.forEach((element, ndx) => { window['myArr' + (ndx + 1)] = [element]; }); console.log(myArr1); console.log(myArr2); console.log(myArr3); 

 var myArray = [1,2,3]; var dynamicArr = new Array(myArray.length); for(var x = 0; x < myArray.length; x++){ var Arr = []; Arr.push(myArray[x]); dynamicArr[x] = Arr; } console.log(dynamicArr) 

var myArray = [1,2,3];
var myarr1=[];
var myarr2=[];
var myarr3=[];
var result = [myarr1, myarr2, myarr3];
function fillInArrays(element, index) {
  result[index].push(element);
}
myArray.forEach(fillInArrays);                                        

console.log(myarr1, myarr2, myarr3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM