2

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;
}

3 Answers 3

2

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));

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

You can use reduce to get the maximum.


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.