skip to Main Content

Current output: [set1, set2, set3]

Desired output: [[set1], [set2], [set3]

Assuming I have variables set1, set2, set3, and an empty array:

arr = [];

I know I can push the variables into my array like so:

array.push(set1, set2, set3);

and if I do console.log(arr) the output will be:

[set1, set2, set3]

But I want to push each variable to its own subarray within the array, so that the output looks like:

[[set1],[set2],[set3]]

I am having a very difficult time figuring out the syntax for this. I’ve tried things like:

array[pos].push(set1)

but this results in a TypeError (Cannot read properties of undefined).

I’ve tried tempArray.splice(tempArray[pos], 0, set1);

but that just results in a single array again.

What is the correct way to push values into a subarray?

3

Answers


  1. You could wrap it in array and push each item:

    const a = 1;
    const b = 2
    const c = 3;
    const arr = [];
    arr.push([a]);
    arr.push([b]);
    arr.push([c]);
    // or in single line like: arr.push([a], [b], [c])
    console.log(arr); //[ [ 1 ], [ 2 ], [ 3 ] ]
    Login or Signup to reply.
  2. Use array literal syntax:

    const set1 = 'set1', set2 = 'set2', set3 = 'set3';
    
    const arr = [];
    
    arr.push([set1], [set2], [set3]);
    
    console.log(arr);

    If your variables come in an array you could map them:

    const set1 = 'set1', set2 = 'set2', set3 = 'set3';
    
    const arr = [];
    
    const scalarArr = [set1, set2, set3];
    
    arr.push(...scalarArr.map(item => [item]));
    
    console.log(arr);
    Login or Signup to reply.
  3. Do it individually.

    arr.push([set1]);
    arr.push([set2]);
    arr.push([set3]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search