0

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 ...>
1
  • With this it will put 00 instead of 21, I need remove that position. Commented Nov 9, 2015 at 12:51

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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));

1 Comment

So if I do arr.slice(24) in my case it will return new arraybuffer without 21 value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.