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]
4 Answers 4
Use concat!
var arr = [0];
var elem = [1, 2, 3];
var newArr = arr.concat([elem]);
console.log(newArr); // => [0,[1,2,3]]
3 Comments
concat is an Array method. It can be called on an array. We are doing it arr.concat. It will parse the given elements. If the given prop is an array like: arr.concat(elem), it would parse all those elements and output: [0,1,2,3,4], but if we put square brackets around the elem array...Now, after you wrote, what you want,
[0, [1, 2, 3]]
you could use at lease three different approaches:
Simple assignment at the end of the array
var arr = [0], elem = [1, 2, 3]; arr[arr.length] = elem; console.log(arr);Array#pushfor pushing a value/object at the end of an array, which is basically the same as above without indicating the place for inserting, but you can use more item for pusing to the array.var arr = [0], elem = [1, 2, 3]; arr.push(elem); console.log(arr);Array#concat, creating a new array with with the given array and the parameters. Here cou need to wrap the content in an array, because concat concatinates arrays.var arr = [0], elem = [1, 2, 3]; arr = arr.concat([elem]); console.log(arr);
1 Comment
arr.concat([elem]) that is workedYou may try to use spread operator to concatenate values of an array.
For example:
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];
console.log(arr2);
//Output: [ 1, 2, 3, 4, 5 ]
1 Comment
you can use this method to push an array into another array
var arr = [0];
var elem = [1, 2, 3];
arr.push(...elem)
console.log(arr); // shows [0, 1, 2, 3];
arr.push(elem)should do exactly what you need.[0, 1, 2, 3]or[0, [1, 2, 3]]?