0

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!!

2
  • 2
    should be array2.indexOf(el) not array2.indexOf(i, el) though it's very heard to understand that first sentence. Commented Feb 16, 2020 at 12:18
  • You are right anyway my fault Commented Feb 16, 2020 at 12:24

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Yeas!! I see, referencing the index to the splice was so simple that I couldn't see it!! Thank you Rory!
Note that the answer removes the last element from array1 for each element of array2 that can't be found in array1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.