Array.prototype.splice and a schoolboy error.

The other day I posted about there being no “delete an arbitrary element” method on Array in Javascrip. The problem being that I tried the solution I am about to present, but made the biggest School Boy Error possible – I didn’t read the documentation correctly!

Whilst I maintain that my solution removes the need to first find the elements, and then delete them (which is better ;). It must be noted that Array.prototype.splice allows you to remove arbitrary elements if you know the index and the number of elements you want to remove.

Anyway, here goes, to remove 1 element from an Array from an arbitrary position:

var values = ["Ah", "hello", "world"];
var result = values.splice(1,1);

This removes the “hello” from the values array in place and returns the elements removed. The result is values = [“Ah”, “world”] and result = [“hello”]

Thanks to @dezfowler

Paul Kinlan

Trying to make the web and developers better.

RSS Github Medium