Reputation: 8347
I have an array which is binded by reference as a model (to handsontable). Let's call it data
. At some point I need to recalc it from scratch (let's call a calced new array freshData
; it may have a different length). Assigning data = freshData
doesn't do the job since this only changes what data
references and doesn't alter the binded model. But calling .splice
and .push
of data
does the job:
data.splice(0,data.length);
for(var i = 0; i < freshData.length; i++)
data.push(freshData[i]);
I wonder: can this be done in a shorter manner? Like, without a loop or may be even using a single method? data.concat(freshData)
doesn't help since it creates a new array, it doesn't change data
itself. Also, this iterating looks somewhat suboptimal in terms of performance...
Upvotes: 2
Views: 197
Reputation: 665100
You can use splice
as a oneliner
data.splice(0, data.length, ...freshData);
Alternatively, use data.length = 0
to empty the array and then put in the new data, either using a loop or passing multiple parameters to push
. Notice that using spread syntax or apply
might overflow the callstack with too large arrays.
Or do it the hard way with assignments:
for (var i=0; i<freshData.length; i++)
data[i] = freshData[i];
data.length = i;
this iterating looks somewhat suboptimal in terms of performance...
No, there's always a need to iterate in some way or another. The time complexity will be linear to the size of the old and new data. But performance shouldn't be your first concern, focus on readability and correctness. If it's actually a tight spot, do your own comparison benchmark to be sure. I'd suspect that my assignment solution would be the fastest, as it doesn't do a method call and tends to avoid array resizing where possible.
Upvotes: 2
Reputation: 17049
If you have ES2015 support OR babel:
data.push(...freshData)
Otherwise just go with
data.push.apply(data, freshData);
Upvotes: 2
Reputation: 1602
You can push the whole array at once without the loop:
data.push(...freshData)
https://runkit.com/arthur/59406f521229b300129a7960
Upvotes: 2