felipesmendes
felipesmendes

Reputation: 47

How to remove position from ArrayBuffer Javascript

I have this ArrayBuffer and need to remove/delete the position of value 21.

I tried to use .splice(24,1) or delete array[24] and didn't work...

What's the correct way to do that?

<Buffer 01 a6 31 35 cb 12 00 08 7d cb b8 ae c5 3e 2d 0e 1e d0 fe 29 4e 61 fd 01 21 a0 00 c0 03 00 00 00 00 00 00 00 00 00 04 24 03 19 15 cb 0b 3b 26 06 0b 31 00 ...>

Upvotes: 0

Views: 4089

Answers (2)

nomve
nomve

Reputation: 735

You cannot change the size of an ArrayBuffer, and so you cannot just delete an element and make it disappear. ArrayBuffer.prototype.slice will give you a copy of the buffer that can be the same size or smaller, so on its own it's no help either.

You could shift all the entries after position N (in your case 24) to the left, overwriting N with N+1, N+1 with N+2 etc. and in the end trimming the last value.

function deleteWithShift(arrayBuffer, position) {
    var typedArray = new Uint8Array(arrayBuffer),
        i;
    for ( i = position+1; i < typedArray.length; i+=1 ) {
        ui8Array[i-1] = ui8Array[i];
    }
    return ui8Array.buffer.slice(0, ui8Array.length-1);
}

You could also slice the buffer twice, before and after the position, and then merge the two arrays.

function deleteWithSliceAndMerge(arrayBuffer, position) {
    var frontValues = new Uint8Array( arrayBuffer, 0, position ),
        backValues = new Uint8Array( arrayBuffer, position+1 ),
        mergedArray = new Uint8Array(frontValues.length + backValues.length);

    mergedArray.set( frontValues );
    mergedArray.set( backValues, position );

    return mergedArray.buffer;
}

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135772

Check out slice():

var buffer = new ArrayBuffer(12);
var dataView = new DataView(buffer);
dataView.setInt8(0, 0x12);
dataView.setInt8(1, 0x34);
dataView.setInt8(2, 0x56);
console.log(dataView.getInt32(0).toString(16)); 
console.log(dataView.getInt8(0).toString(16));
var dataView = new DataView(buffer.slice(1));
console.log(dataView.getInt32(0).toString(16)); 
console.log(dataView.getInt8(0).toString(16));

Upvotes: 0

Related Questions