javascript - removing duplicate objects in an array, keeping ones with maximum property value -
i have array this:
const array=[ {id:0, quantity:1}, {id:1, quantity:2}, {id:0, quantity:4} ]
my goal this:
const array=[ {id:1, quantity:2}, {id:0, quantity:4} ]
the order of object not matter long can find 'id' larger quantity
i tried filter + findindex, map +filter, etc kept making mistake. need help.
you use hash table , check if object same id
in result set. if actual quantity greater, assign actual object.
var array = [{ id: 0, quantity: 1 }, { id: 1, quantity: 2 }, { id: 0, quantity: 4 }], hash = object.create(null), unique = array.reduce(function (r, o) { if (!(o.id in hash)) { hash[o.id] = r.push(o) - 1; return r; } if (o.quantity > r[hash[o.id]].quantity) { r[hash[o.id]] = o; } return r; }, []); console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comments
Post a Comment