Home > Net >  remove duplicate from array of objects based on condition
remove duplicate from array of objects based on condition

Time:10-09

I have this array of objects I have tried to remove a duplicate from the array, but I can't remove it based on a condition this is the array

result = [
  { jobId: 2, requiredNumber: 2, acceptableRate: 80 },
  { jobId: 3, requiredNumber: 3, acceptableRate: 80 },
  { jobId: 4, requiredNumber: 1, acceptableRate: 80 },
  { jobId: 2, requiredNumber: 1, acceptableRate: 95 } 
]

what I have done is using the .filter() and the .findIndex() but I can't get my excepted output this is what I have done

var mm = result.filter(
  (value, index, self) =>
    index === self.findIndex((t) => t.jobId === value.jobId)
);
console.log(mm);

my output was

[
  { jobId: 2, requiredNumber: 2, acceptableRate: 80 },
  { jobId: 3, requiredNumber: 3, acceptableRate: 80 },
  { jobId: 4, requiredNumber: 1, acceptableRate: 80 }
]

expected output is based on my condition which can be based on higher acceptableRate or higher requiredNumber

[
  { jobId: 2, requiredNumber: 1, acceptableRate: 95 },
  { jobId: 3, requiredNumber: 3, acceptableRate: 80 },
  { jobId: 4, requiredNumber: 1, acceptableRate: 80 },
]

CodePudding user response:

First sort the array by acceptableRate or if they are the same values by requiredNumber then find duplicates. This way.

result = [
    { jobId: 2, requiredNumber: 2, acceptableRate: 80 },
    { jobId: 3, requiredNumber: 3, acceptableRate: 80 },
    { jobId: 4, requiredNumber: 1, acceptableRate: 80 },
    { jobId: 2, requiredNumber: 1, acceptableRate: 95 },
];

 result.sort(function (a, b) {
     return b.acceptableRate - a.acceptableRate || b.requiredNumber - a.requiredNumber;
 });

var mm = result.filter(
    (value, index, self) =>
        index === self.findIndex((t) => t.jobId === value.jobId),
);

console.log(mm);

CodePudding user response:

The following code will filter the values ​​for you if the jobId comes first according to acceptableRate, and if there are two identical values ​​then it will filter according to requiredNumber

var mm = result.sort((a, b) => b.jobId < a.jobId ? true : b.jobId > a.jobId ? false : b.acceptableRate > a.acceptableRate ? true : b.acceptableRate < a.acceptableRate ? false : b.requiredNumber - a.requiredNumber);

CodePudding user response:

If I understood your question right, here might be the code. We filter out all the items if there's an item with same jobId and higher acceptableRate.

const result = [
  { jobId: 2, requiredNumber: 2, acceptableRate: 80 },
  { jobId: 3, requiredNumber: 3, acceptableRate: 80 },
  { jobId: 4, requiredNumber: 1, acceptableRate: 80 },
  { jobId: 2, requiredNumber: 1, acceptableRate: 95 } 
];

const finalResult = result.filter(x => 
    !result.find(r => 
        r.jobId === x.jobId && 
        r.acceptableRate > x.acceptableRate));
console.log(finalResult);

  • Related