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
You could wrap it in array and push each item:
Use array literal syntax:
If your variables come in an array you could map them:
Do it individually.