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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -