Is there or is there ever going to be an equivalent of Array.prototype.splice
for TypedArrays?
I want to be able to delete a range of items from a TypedArray.
So TypedArrays in ES6 are not classical Javascript arrays, but closer to an API for a underlying binary buffer (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays).
Since splice
mutates the actual length of array it isn't usable with TypedArrays (http://www.es6fiddle.net/idt0ugqo/).
You can create similar behavior by creating your own splice (although it will be slower).
This is a simple equivalent except that it doesn't account for all nuances of `splice. As @bergi commented, I don't allow negative values.
function splice(arr, starting, deleteCount, elements) {
if (arguments.length === 1) {
return arr;
}
starting = Math.max(starting, 0);
deleteCount = Math.max(deleteCount, 0);
elements = elements || [];
const newSize = arr.length - deleteCount + elements.length;
const splicedArray = new arr.constructor(newSize);
splicedArray.set(arr.subarray(0, starting));
splicedArray.set(elements, starting);
splicedArray.set(arr.subarray(starting + deleteCount), starting + elements.length);
return splicedArray;
};
splice(new Uint8Array([1,2,3]), 0, 1); // returns Uint8Array([1,3])
http://www.es6fiddle.net/idt3epy2/
Is there or is there ever going to be an equivalent of
Array.prototype.splice
forTypedArrays
?
No, because TypedArrays
cannot change their size. There's no push
/pop
/shift
/unshift
methods either.
If you want to delete elements from your array, you typically set them to null, and care for those nulls when traversing the array. This also avoids having to shift around all elements after the ones being deleted.
If you really need this, your best bet is to create a new array and copy elements over it (the ones before the deleted section, the new ones, and then the ones after the deleted section). @cdbitesky has given a nice implementation for this.
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