Skip to content

Instantly share code, notes, and snippets.

@GrayedFox
Last active January 9, 2023 11:58
Show Gist options
  • Save GrayedFox/524b8a430c0e67d094a121b9e62c3eef to your computer and use it in GitHub Desktop.
Save GrayedFox/524b8a430c0e67d094a121b9e62c3eef to your computer and use it in GitHub Desktop.
Array.remove safe polyfill
// remove the first instance of an item inside an array (extends native array object)
if (!Array.prototype.remove) {
Array.prototype.remove = function remove (item) { // eslint-disable-line no-extend-native
if (!(this || Array.isArray(this))) {
throw new TypeError()
}
if (this.indexOf(item) !== -1) {
this.splice(this.indexOf(item), 1)
return this
}
// handles cases where item is a finite index and element at given index is defined
if (typeof this[item] !== 'undefined' && item >= 0 && Number.isFinite(item)) {
this.splice(item, 1)
return this
}
}
}
@DerZyklop
Copy link

afaik this.includes(item) is exactly the same as this.indexOf(item) !== -1. So this.indexOf(item) !== -1 is obsolete.
https://gist.github.com/GrayedFox/524b8a430c0e67d094a121b9e62c3eef#file-arrayremovemethod-js-L8

@GrayedFox
Copy link
Author

They are nearly the same!

However Array.prototype.indexOf uses strict equality whereas Array.prototype.includes uses the same-value-zero algorithm which behaves differently for NaN. I wanted the polyfill to account for NaN and return true in this instance - but as that's the only difference I can indeed remove the includes check - so not quite exactly the same but in this case superfluous as comparisons of all other types return the same result - and indexOf has IE9 and older support which is sort of the point of a polyfill I guess.

Thanks for pointing it out 👍

@DerZyklop
Copy link

Happy new year,
(…happy reading-all-the-forgotton-github-notifications-from-last-year LOL)

Thanks for enlightening me. There is always something new to learn about JavaScript - even after decades :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment