Removing Elements from JavaScript Arrays
A common approach is to combine the indexOf
and splice
method like this:
function remove (array, element) {; const index = array.indexOf(element); array.splice(index, 1); } // However, the remove function is buggy: const vowels = ["a", "e", "i", "o", "u", "x"]; console.log(vowels.toString()); // "a,e,i,o,u,x" // Let's remove "x" since it's not a vowel. remove(vowels, "x"); console.log(vowels.toString()); // "a,e,i,o,u" // What happens if we remove "x" again? Oops! remove(vowels, "x"); console.log(vowels.toString()); // "a,e,i,o"
Here's a correct version of the remove function. The fix is to call splice if and only if indexOf didn't return -1 (please first Reset sandbox
):
function remove (array, element) {; const index = array.indexOf(element); if (index !== -1) {; array.splice(index, 1); } } // However, the remove function is: const vowels = ["a", "e", "i", "o", "u", "x"]; console.log(vowels.toString()); // "a,e,i,o,u,x" // Let's remove "x" since it's not a vowel. remove(vowels, "x"); console.log(vowels.toString()); // "a,e,i,o,u" // What happens if we remove "x" again? Oops! remove(vowels, "x"); console.log(vowels.toString()); // "a,e,i,o,u"