function removeElement(array, elementToRemove) { for (let i = 0; i < array.length; i++) { if (array[i] === elementToRemove) { array.splice(i, 1); } } } let myArray = [1, 2, 3, 2, 4]; removeElement(myArray, 2);
function removeElement(array, elementToRemove) { for (let i = 0; i < array.length; i++) { if (array[i] === elementToRemove) { array.splice(i, 1); } } } let myArray = [1, 2, 3, 2, 4]; removeElement(myArray, 2);
This solution isn’t ideal since it doesn’t account for the fact that the array is being modified as it’s being iterated over. When the element at index 1 is removed, the element at index 2 is shifted to index 1.
There are a bunch of ways to make this better, all with varying tradeoffs. This is probably the best one, which uses JavaScript’s filter method to return a new array after filtering out the elementToRemove.
function removeElement(array, elementToRemove) { return array.filter((element) => element !== elementToRemove); }