Is there a nondestructive alternative to splice?
I'd like to keep a bank of data for a series are stripcharts. While I may have ~10,000 data points, perhaps I would only like to show 100 at a time as the user scrolls with a scrollbar. So if I have
var data = [];
// ... fill data with ~1000 data points
// ... data periodically updated and appended
stripchart.draw( data.splice(-100,100) ); // get last 100 data points
But I've destroyed my data, as splice is destructive. So... What's the slickest solution to grabbing a window of the data?
splice() The . splice() method is a destructive array method, which means it modifies the array on which it is called (disclaimer: destructive methods can be risky, especially if you use the array in question elsewhere in your program, so proceed with caution).
slice returns a piece of the array but it doesn't affect the original array. splice changes the original array by removing, replacing, or adding values and returns the affected values. When you use each one is up to you.
Slice is used to get a new array from the original array whereas the splice is used to add/remove items in the original array. The changes are not reflected in the original array in the case of slice and in the splice, the changes are reflected in the original array.
The splice() methods mutate an array by either adding to the array or removing from an array and returns only the removed items.
Use slice
instead. It's like substr
for arrays ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With