Reputation: 57
I have 2 arrays, I want to delete the elements from first array with the second ones just once conserving the other duplicates that might be:
array1 = [1,1,1,1,2,2,2,2];
array2 = [1,1,2];
//resultingArray = [1,1,2,2,2];
It seems that all the answers I got are about removing duplicates while searching for this..
I'm wondering if there's a way to do this with filter
, but it only seems to filter all the entries
resultingArray = array1.filter(function(el){
return array2.indexOf(el) === -1;
});
//resultingArray = [];
Another way that I could think of is removing each one of the array elements one by one like this
for( var i = 0; i < arr.length; i++){
if ( arr[i] === Number) {
arr.splice(i, 1);
i = arr.length;
};
But it doesn't seem to be a great way to do this?
And again the difference between those arrays will remove all the duplicated elements
Would appreciate to know the best method for this or directions to a duplicated posts that i couldn't find!!
Upvotes: 0
Views: 583
Reputation: 337743
To achieve this you can loop through array2
removing the first matching item matching the current value in array1
. Something like this:
let array1 = [1,1,1,1,2,2,2,2];
let array2 = [1,1,2];
array2.forEach(i => array1.splice(array1.indexOf(i), 1));
console.log(array1);
Upvotes: 1