To remove all instances of a value from an array in JavaScript, the easiest way is to use the JavaScript array filter() function.
Below shows an example of how you could remove the number ‘1’ from an array of numbers with filter().
var array_of_numbers = [1,2,3,4,1,2,1,4,3,2];
var filtered_array = array_of_numbers.filter(x => x != 1);
console.log(filtered_array);
// Output:
[2, 3, 4, 2, 4, 3, 2]
If you want to be more explicit with the callback function to filter(), you can do the following.
var array_of_numbers = [1,2,3,4,1,2,1,4,3,2];
var filtered_array = array_of_numbers.filter(function(x) {
return x != 1;
});
console.log(filtered_array);
// Output:
[2, 3, 4, 2, 4, 3, 2]
When working with arrays in JavaScript, it can be valuable to be able to easily filter and remove unwanted values from your array.
One such situation is where you may want to remove all instances of a certain value from an array.
We can easily remove all instances from an array of a value in JavaScript using the JavaScript array filter() function.
To use filter(), you need to pass a callback function which will provide logic to identify the value or values you want to remove.
Below are a few more examples of how you can use filter() to filter out values from arrays in JavaScript.
If you have an array of strings, you can easily filter out any empty strings with filter().
var array_of_strings = ["This","","is","an","array","","with","empty","","strings","."];
var filtered_array = array_of_strings.filter(x => x != "");
console.log(filtered_array);
// Output:
['This', 'is', 'an', 'array', 'with', 'empty', 'strings', '.']
Using filter() to Remove and Filter Out Unwanted Values in JavaScript Array
The JavaScript filter() function is extremely useful and powerful when working with arrays in JavaScript.
If needed, you can pass complex conditional statements in the callback function for filter().
var array_of_strings = ["This","","is","an","array","","with","empty","","strings","."];
var filtered_array = array_of_strings.filter(x => !["This",""].includes(x));
console.log(filtered_array);
// Output:
['is', 'an', 'array', 'with', 'empty', 'strings', '.']
filter() also works on arrays of JavaScript objects and you can filter based on the names of the object.
var array_of_js_objects = [{"name":"Jim","age":30},{"name":"Sally","age":20},{"name":"Paul","age":25},{"name":"Suzie","age":35}];
var filtered_array = array_of_js_objects.filter(x => x["age"] > 25 && x["name"][0] == "J");
console.log(filtered_array);
// Output:
[{name: 'Jim', age: 30}]
Hopefully this article has been useful for you to learn how to remove all instances from an array in JavaScript.
Leave a Reply