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!

4
  • I'm still not clear what the question is. Could you please explain more? Commented Jun 21, 2019 at 20:31
  • I would review solutions to this answer here: stackoverflow.com/questions/1669190/… Commented Jun 21, 2019 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 Commented Jun 21, 2019 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]); Commented Jun 21, 2019 at 20:49

1 Answer 1

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Could you tell me this but that is not ES6? I'm working on something that does not allow to develop in es6
Added Es5 version

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.