Home > front end >  How to convert array to array of array in Javascript?
How to convert array to array of array in Javascript?

Time:12-29

How to convert single array to array of array?

This is below present code, which is not working

array1 = ['a', 'b', 'c', 'd', 'e'];
array2 = [];

onClick() {
 this.array2 = this.array2.push(this.array1);
 console.log(this.array2);
}

Desired output is

array2  = [['a', 'b', 'c', 'd', 'e']];

CodePudding user response:

You only need to remove variable from pushing statement. like

 array2.push(array1);
 console.log(array2);

const array1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = [];
arr2.push(array1);
console.log(arr2);

CodePudding user response:

You can do that simply with const array2 = [array1];

CodePudding user response:

use this:

this.array1 = ['a','b','c','d','e']
this.array2 = []
onClick() {
    this.array2.push(this.array1);
}

Explanation: Not using 'this' will make you a global variable, where the object's (this) array1 and array2 will remain a undefined. So you need to declare array1 and array2 in the object by using 'this' before the two declarations.

CodePudding user response:

You have to extract first array and push the elements of first array to second array. Here down is little example.

const array1  = ['a', 'b', 'c', 'd', 'e'];
const array2  = [];
 
for(const i of array1) {
    array2.push(i);
}
 
console.log(array2);

  • Related