Getting objects with maxBy with same values

1k Views Asked by At

I have this array:

const obj = [
  {
    value: 1,
    position: 1,
    id: 333,
  },
  {
    value: 1,
    position: 2,
    id: 222,
  },
];

I'm using maxBy from lodash to get the max value of the attribute called value.

_.maxBy(obj, "value");

So, the problem is that there are two objects with the same value attribute and the maxBy is showing me the last object. In this case, I would need to make the maxBy and the same time, referring the less value to the position attribute.

Any help ?

1

There are 1 best solutions below

0
On

_.maxBy accepts iteratee as second params, we can custom the iteratee. Your current way is using the _.property iteratee shorthand.

The solution for your case:

const arr = [
  {
    value: 1,
    position: 1,
    id: 333,
  },
  {
    value: 1,
    position: 2,
    id: 222,
  },
];

const result = _.maxBy(arr, (i) => {
  const isDuplicate = _.filter(arr, (o) => o.value === i.value).length;
  return i.value - (isDuplicate ? i.position : 0); // get max value of (i.value - i.position) when we get duplicate case.
});
console.log(result);

In your case, to get max value of (i.value - i.position), we need max value of value and min value of position.