How to add new elements to an array without overwriting the first one?
I'm trying to add new elements to an Array but it keeps overwriting it the first element, i'm not sure if i'm doing it correctly, but this is my code:
push
method is ok for you. It will add elements at the end of the array. If you have data already setted in your array, then remove this.nArray =
because this is creating a new empty array, deleting all previous data stored in nArray
variable. In any case, if you want to add elements at the beginning try unshift
: this.nArray.unshift(this.data);
.
If you push data
inside nArray
you will get an array of array of objects. Maybe you are looking to add only the elements in data
and not the whole array. Use concat
method for that.
this.nArray.push(this.nArray.concat(data));
Or a shorten syntax using spread operator ...
:this.nArray.push(...data);
NOTE:
I'd recommend you to use const
for your array definition and remove the blank assignment of in
nArray
. Also, instead of using concat
, use the spread operators with the push
method.
As it is, you are pushing an array to an empty array. So, there is nothing like overriding here. However, assuming this.nArray
is filled with some elements already, you should use the spread syntax for concatenating two arrays like:
Use concat when you want to merge two arrays.
You can now use the new merged array for your purpose
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.