Remove a specific array element
How to solve it
To remove all elements in an array that have a specific value, we will use the array.filter method. This method is used to filter array elements based on certain conditions. This can be applied to our problem.
The array.filter method is called with a function that is applied to each element of the array. In order to keep an element, the function must return true. In order to remove it, the function must return false.
In the following example, we apply the array.filter method to an array. As parameter, we pass a function that always returns true. Therefore, no filtering is taking place. This returns a new array with all the elements of the original array:
const arr = [0,1,2,3,4]; console.log(arr.filter(() => true)); // output: [0,1,2,3,4]
What we do inside the function is completely up to us, as long as we return true or false. For example, we could randomly return true or false in order to create a random sample of the array.
But, we could also apply certain checks on the array elements to decide whether they should be removed or not. We can do this because in each call, the function has access to the array element that is being processed.
In the following example we keep all array elements that have a value equal to 3.
const arr = [0,1,2,3,4]; console.log(arr.filter((elem) => elem === 3)); // output: [3]
In the challenge above, the task is to remove all elements that have a value equal to a certain value. Therefore, you will have to slightly adjust the code.