Prem
Prem

Reputation: 5997

How to group by and get the element having max value - javascript/node.js

I have the following array. I am trying to get the element having maximum id by grouping by the entryId in node.js.

[
    {
        "entryId": "7wpNAXhYI",
        "id": 5
    },
    {
        "entryId": "7wpNAXhYI",
        "id": 6
    },
    {
        "entryId": "5PGB23RI",
        "id": 7
    },
    {
        "entryId": "5PGB23RI",
        "id": 8
    }
]

The typical sql syntax would like as follows:
select entryId, max(id) from table group by entryId

I have written the following code which would get just the max without grouping by. Any help how to modify the following code or any simple approach available.

function getMax(array) {
  var max = {};
  for (var i = 0; i < array.length; i++) {
    if (parseInt(array[i].id) > (parseInt(max.id) || 0))
      max = array[i];
  }
  return max;
}

Upvotes: 2

Views: 2615

Answers (3)

thuva4
thuva4

Reputation: 1225

You can use reduce to get the maximum.


function getMax(arr) {
      max = arr.reduce((M, o) => M > o.id ? M : o, {id:-Infinity});
}

Upvotes: 1

Eddie
Eddie

Reputation: 26844

You can use 2 reduce the first one is to group the array. The second one is to get the max using Math.max()

var arr = [{"entryId":"7wpNAXhYI","id":5},{"entryId":"7wpNAXhYI","id":6},{"entryId":"5PGB23RI","id":7},{"entryId":"5PGB23RI","id":8}]
var result = Object.entries(arr.reduce((c, {entryId,id}) => {
  (c[entryId] = c[entryId] || []).push(id);
  return c;
}, {})).reduce((c, [k, v]) => Object.assign(c, {[k]: Math.max(...v)}), {});

console.log(result);

You can use map if you prefer an array:

var arr = [{"entryId":"7wpNAXhYI","id":5},{"entryId":"7wpNAXhYI","id":6},{"entryId":"5PGB23RI","id":7},{"entryId":"5PGB23RI","id":8}]

var result = Object.entries(arr.reduce((c, {entryId,id}) => {
  (c[entryId] = c[entryId] || []).push(id);
  return c;
}, {})).map(([entryId, id]) => ({entryId,id: Math.max(...id)}))

console.log(result);

Upvotes: 2

ellipsis
ellipsis

Reputation: 12152

You can use sort in descending order and return the first element

var a = [{
    "entryId": "7wpNAXhYI",
    "id": 5
  },
  {
    "entryId": "7wpNAXhYI",
    "id": 6
  },
  {
    "entryId": "5PGB23RI",
    "id": 7
  },
  {
    "entryId": "5PGB23RI",
    "id": 8
  }
]


function getMax(array) {
  return array.sort((a, b) => b.id - a.id)[0]
}
console.log(getMax(a));

Upvotes: 2

Related Questions