I am trying that in this array there are only objects that do not have the duplicate _id property and also have the amount property with the largest number that there is between the duplicate objects.
const array = [
{ _id: '12398gsbya', amount: 1 },
{ _id: '12398gsbya', amount: 2 },
{ _id: '12398gsbya', amount: 3 },
{ _id: '12398gsbya', amount: 1 },
{ _id: '12398gsbya', amount: 2 },
{ _id: '12398gsbya', amount: 3 },
{ _id: 'f9h8gasd90', amount: 1 },
{ _id: 'f9h8gasd90', amount: 2 },
{ _id: '12398gsbya', amount: 1 },
{ _id: '12398gsbya', amount: 2 },
{ _id: '12398gsbya', amount: 3 },
{ _id: 'f9h8gasd90', amount: 1 },
{ _id: 'f9h8gasd90', amount: 2 },
{ _id: 'f9h8afgh80', amount: 1 }
];
The result I am looking for would be like this:
const array = [
{ _id: '12398gsbya', amount: 3 },
{ _id: 'f9h8gasd90', amount: 2 },
{ _id: 'f9h8afgh80', amount: 1 }
];
This is what I tried but I can't get it to return the duplicates with the highest amount property.
var hash = {};
let arrayWithoutDuplicates = arrayWithDuplicates.filter(function(currentValue){
console.log(currentValue)
var exists = !hash[currentValue._id]
hash[currentValue._id] = true;
return exists;
})
console.log(arrayWithoutDuplicates)
[
{ _id: '12398gsbya', amount: 1 },
{ _id: 'f9h8gasd90', amount: 1 },
{ _id: 'f9h8afgh80', amount: 1 }
]