Reputation: 131
I Have 2 array like this
arr = ["9138172", "9138214", "9138238"]
array = ["9138172", "9138238"]
how can I remove values in array
from arr
?
I want to obtain
arr = ["9138214"]
Maybe I can use splice()
?
Upvotes: 0
Views: 175
Reputation: 30739
You can use Array.forEach()
to loop over to the array of items and then check that each item exist in array
array. If so use splice()
. Use simple function and indexOf()
as it will work in old browsers and also in IE.
var arr = ["9138172", "9138214", "9138238"];
var array = ["9138172", "91382142"];
var i = arr.length;
while (i--) {
if (array.indexOf(arr[i]) !== -1) {
arr.splice(i, 1);
}
}
console.log(arr);
Upvotes: 3
Reputation: 29
If you want to lodash, this can be easily done by the difference function:
https://lodash.com/docs/4.17.10#difference
import {difference} from 'lodash';
arr = ["9138172", "9138214", "9138238"]
array = ["9138172", "9138238"]
console.log(difference(arr, array));
Upvotes: 0
Reputation: 22474
You can use .filter()
for that.
Here is an example:
var arr = ["9138172", "9138214", "9138238"];
var array = ["9138172", "9138238"];
arr = arr.filter(e => !array.includes(e));
console.log(arr)
The code above just filters the arr
array and keeps only elements that are not present in the array
. The .includes()
function that I've used works on these arrays because they contain strings, if you're dealing with objects, you need to find some other way of checking if array
contains the element.
Upvotes: 2