Search code examples
javascriptarraysinsert

How to push array into another array as one element


I'm new in JS, can't find solution to do something like that

var arr = [0];
var elem = [1, 2, 3];
???
console.log(arr); // shows [0, [1, 2, 3]];

I've tried with .push(elem), JS decides that I passed array of values (not a single one), and concatenate content of arr and elem arrays, so that the result is [0, 1, 2, 3]


Solution

  • Use concat!

    var arr = [0];
    var elem = [1, 2, 3];
    var newArr = arr.concat([elem]);
    console.log(newArr); // => [0,[1,2,3]]