Remove multiple values from an array in JavaScript
This post will discuss how to remove multiple values from an array in JavaScript. The solution should create a new array that excludes the specified values.
1. Using Array.prototype.filter() function
The idea is to use JavaScript filter() method to remove multiple items from an array. The following code example returns the new array of filtered values using the latest includes() method.
|
1 2 3 4 5 6 7 8 9 |
let arr = [ 2, 3, 5, 8, 4 ]; let values = [ 2, 4 ]; arr = arr.filter(item => !values.includes(item)); console.log(arr); /* Output: [ 3, 5, 8 ] */ |
Here’s an alternative version which uses the indexOf() method instead of the includes() method.
|
1 2 3 4 5 6 7 8 9 |
let arr = [ 2, 3, 5, 8, 4 ]; let values = [ 2, 4 ]; arr = arr.filter(item => values.indexOf(item) === -1); console.log(arr); /* Output: [ 3, 5, 8 ] */ |
2. Using Lodash/Underscore Library
This solution involves using external JavaScript libraries. The Underscore and Lodash library offer the _.without method, which returns a copy of the array excluding the specified values.
Here’s a simple example for removing multiple elements from the array using the _.without method
|
1 2 3 4 5 6 7 8 9 10 11 |
var _ = require('lodash'); // or underscore let arr = [ 2, 3, 5, 8, 4 ]; let values = [ 2, 4 ]; arr = _.without(arr, ...values); console.log(arr); /* Output: [ 3, 5, 8 ] */ |
Alternatively, you can use the _.difference method, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 |
var _ = require('lodash'); // or underscore let arr = [ 2, 3, 5, 8, 4 ]; let values = [ 2, 4 ]; arr = _.difference(arr, values); console.log(arr); /* Output: [ 3, 5, 8 ] */ |
That’s all about removing multiple values from an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)