以数组中的最小值获取对象

时间:2019-06-21 20:27:55

标签: javascript

我有一个无法解决的小问题。 我需要一些在javascript中仅接受数组中最接近零的值的东西。 数组如下:

[{priority: 0, instance: "DNI"},
{priority: 1, instance: "CUIT"},
{priority: 2, instance: "CEDULA_IDENTIDAD"}]

我需要的是仅适用于以下功能:

{priority: 0, instance: "DNI"}

谢谢!

1 个答案:

答案 0 :(得分:0)

鉴于优先级不会变为负数,您可以使用简单的reduce

const queue = [{ priority: 0, instance: "DNI" },
            { priority: 1, instance: "CUIT" },
            { priority: 2, instance: "CEDULA_IDENTIDAD" }];

const minObject = queue.reduce((p, c) => {
    return p.priority < c.priority ? p : c;
});

ES5:

var queue = [{
  priority: 0,
  instance: "DNI"
}, {
  priority: 1,
  instance: "CUIT"
}, {
  priority: 2,
  instance: "CEDULA_IDENTIDAD"
}];

var minObject = queue.reduce(function (p, c) {
  return p.priority < c.priority ? p : c;
});