Page 1 of 1

Push an array into the same array JS

Posted: 12 Nov 2020, 12:13
by Marius
I'm trying to push an array into the same array in javascript, But it doesn't seem to be working; the third element is added continuously.
Here is my code so far:

Code: Select all

var arr = ['Hello', 'World!']
arr.push(arr);
console.log(arr);
Expected output: ['Hello', 'World!', ['Hello', 'World!']]

Does somebody know why my code doesn't work, and how to fix it?

Push an array into the same array JS

Posted: 12 Nov 2020, 14:14
by Admin
You are trying to push the same reference to the array. So, when the array updated later, the array inside the element will be updated as well.
To fix this, you need to push a copy of the array (another reference).
See the sample below.

Code: Select all

var arr = ['Hello', 'World!']
arr.push([...arr]);
console.log(arr);