Romain Gaget
Romain Gaget

Reputation: 97

From an array of objects, how to return property `b` of the object that has the highest property `a`?

I need to get the value of the property b from the object with the highest value of the property a.

var myArr = [
  {
    a: 1,
    b: 15
  },
  {
    a: 2,
    b: 30
  }
];

I tried the following, but it just returns the highest value of a, rather than of b.

var res = Math.max.apply(Math,myArr.map(function(o){return o.a;});
var blah = getByValue(myArr);

Upvotes: 5

Views: 421

Answers (4)

Xiaohang
Xiaohang

Reputation: 1

Try this:

var myArr = [
    {
        a: 1,
        b: 15
    },
    {
        a: 2,
        b: 30
    }
];

var res = myArr.map(function(o){return o.b;});

myArr.sort(function (o1, o2) {
    return o1.a < o2.a;
})

console.log(myArr[0].b);

Upvotes: 0

Angelos Chalaris
Angelos Chalaris

Reputation: 6707

Using reduce

You can use .reduce() to find the element with the maximum a value and then just grab its b value, like this:

var myArr = [{
    a: 1,
    b: 15
  },
  {
    a: 2,
    b: 30
  }
];

var max = myArr.reduce(function(sum, value) {
  return (sum.a > value.a) ? sum : value;
}, myArr[0]);

console.log(max.b);

Using sort

A bit more unorthodox approach is to use .sort() to sort the array in descending order in terms of its property a and then get the first element's b value, like this:

var myArr = [{
    a: 1,
    b: 15
  },
  {
    a: 2,
    b: 30
  }
];

var max = myArr.sort(function(value1, value2) {
  return value1.a < value2.a;
})[0];

console.log(max.b);

Upvotes: 0

charlietfl
charlietfl

Reputation: 171698

Can sort a copy then get first or last depending on sort direction:

var myArr = [
  {
    a: 1,
    b: 15
  },
  {
    a: 2,
    b: 30
  }
];

var highest = myArr.slice().sort((a,b)=>a.a-b.a).pop().b

console.log(highest)

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 193358

Use Array#reduce, and on each iteration take the object with the highest a value:

var myArr = [{"a":1,"b":15},{"a":2,"b":30}];

var result = myArr.reduce(function(o, o1) {
  return o.a > o1.a ? o : o1;
}).b;

console.log(result);

Upvotes: 9

Related Questions