Remove Specific Non-Contiguous Elements from an Array
Let's define the function removeElements
to remove specific values from an array:
function removeElements(array, elementsToRemove) { // Function body will go here }
To remove the specific values in elementsToRemove
from the array, we will use the filter
method.
This method creates a new array with all elements that pass the test implemented by the provided function. In our case, the test will check if an element is not present in elementsToRemove
.
function removeElements(array, elementsToRemove) { // Filter the array to exclude elements present in elementsToRemove return array.filter(item => !elementsToRemove.includes(item)); }