0

I'm with a small problem that can not be solved. I need something in javascript that takes only the value closest to zero in an array. The array is the following:

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

What I need, is some function that stays only with:

{priority: 0, instance: "DNI"}

thank you!

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
nicounyi
  • 43
  • 1
  • 4
  • I'm still not clear what the question is. Could you please explain more? – Dhaval Jardosh Jun 21 '19 at 20:31
  • I would review solutions to this answer here: https://stackoverflow.com/questions/1669190/find-the-min-max-element-of-an-array-in-javascript – prufrofro Jun 21 '19 at 20:34
  • @DhavalJardosh What I need is to save the object with the value "property" closest to 0 to a variable, or to be 0 – nicounyi Jun 21 '19 at 20:35
  • If the priority can have a negative value and you want the closest to zero object: `data = [{...}]; data.reduce((p, c) => Math.abs(c.priority) - Math.abs(p.priority) < 0 ? c : p, data[0]);` – Rancbar Jun 21 '19 at 20:49

1 Answers1

0

Given that priority doesn't become negative, You can do it using simple 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;
});
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35