如何分组并获得具有最大值的元素-javascript / node.js

时间:2019-05-19 06:37:48

标签: javascript node.js

我有以下数组。我试图通过按printf("%s", digit_words[digit])中的entryId分组来获得具有最大id的元素。

node.js

典型的sql语法如下:
[ { "entryId": "7wpNAXhYI", "id": 5 }, { "entryId": "7wpNAXhYI", "id": 6 }, { "entryId": "5PGB23RI", "id": 7 }, { "entryId": "5PGB23RI", "id": 8 } ]

我编写了以下代码,无需分组即可获得最大值。任何有关如何修改以下代码的帮助或任何可用的简单方法。

select entryId, max(id) from table group by entryId

3 个答案:

答案 0 :(得分:2)

您可以按降序使用sort并返回第一个元素

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

答案 1 :(得分:2)

您可以使用2 reduce,第一个是对数组进行分组。第二个是使用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);

如果需要数组,可以使用map

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

答案 2 :(得分:1)

您可以使用reduce来获得最大值。


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