Last active
January 29, 2025 00:41
-
-
Save GrayedFox/524b8a430c0e67d094a121b9e62c3eef to your computer and use it in GitHub Desktop.
Array.remove safe polyfill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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