Vikas Vanvi
Vikas Vanvi

Reputation: 462

Remove only first duplicate value and all other matching values after comparing two arrays

I have two array , I am trying to remove all matching value from 1st array which are in 2nd. But if value is duplicate it should only remove 1st duplicate value.

For example - my two arrays are

arr1=[1,1,2,3,4,4]
arr2=[1,3,4]

it should give result as = [1,2,4]

or if my arrays are

arr1=[1,1,1,2,3,4,4,4]
arr2=[1,3,4]

it should give result as = [1,1,2,4,4]

I tried different approach using filter and includes but nothing works. Below code removes all matching values but I want to remove all matching and only first duplicate value if it matches.

  arr1 =
    arr1.filter(f => !arr2.includes(f));

Upvotes: 0

Views: 98

Answers (4)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Use Set and reduce

const process = (arr1, arr2) => {
  const set2 = new Set(arr2);
  return arr1.reduce((acc, curr) => {
    set2.has(curr) ? set2.delete(curr) : acc.push(curr);
    return acc;
  }, []);
};

let arr1 = [1, 1, 2, 3, 4, 4];
let arr2 = [1, 3, 4];
console.log(process(arr1, arr2));


arr1=[1,1,1,2,3,4,4,4]
arr2=[1,3,4]
console.log(process(arr1, arr2));

Upvotes: 0

Rahul Kant
Rahul Kant

Reputation: 33

There are lots of ways to do this. Most of the above answers are right. But I would suggest using sets

let arr1 = [1, 1, 2, 3, 4, 4];
let arr2 = [1, 3, 4];
let result = [];

for(let i = 0; i < arr1.length; i++) {
   let index = arr2.indexOf(arr1[i]);
   if(index > -1) {
      arr2.splice(index, 1);
   } else {
     result.push(arr1[i]);
   }
}

console.log(result); /// [1, 2, 4]

Upvotes: 0

user11785418
user11785418

Reputation:

In order to remove only the first occurrence, you can use indexOf instead. So, the solution would be:

let arr1 = [1, 1, 2, 3, 4, 4];
let arr2 = [1, 3, 4];

for (let i = 0; i < arr2.length; i++) {
  if (arr1.includes(arr2[i])) {
    let matchedItemIndex = arr1.indexOf(arr2[i]);
    arr1[matchedItemIndex] = null;
  }
}

arr1 = arr1.filter((x) => x != null);
console.log(arr1); // Expected Result: [1, 2, 4]

Upvotes: 1

Eliseo
Eliseo

Reputation: 57939

  this.arr2.forEach(x=>{
    if (this.arr1.indexOf(x)>=0)
      this.arr1.splice(index,1)
  })

or

  this.arr1=this.arr1.filter((x,index)=>this.arr2.indexOf(x)<0 ||
        this.arr1.indexOf(x)!=index )

Upvotes: 3

Related Questions