Returning the object from the array with the highest property value

we need to get the b value from the object with the highest a value ...

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

      

we tried the following, but it just returns the maximum value of a, not b.

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

var blah = getByValue(myArr);

      

+3


source to share


4 answers


Use Array # to shrink , and on each iteration take the object with the highest value a

:



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

Run codeHide result


+7


source


You can sort the copy, then get the first or last, depending on the sorting 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)
      

Run codeHide result


+1


source


Using abbreviation

You can use .reduce()

to find the element with the maximum value a

and then just get its value b

like:

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

Run codeHide result


Using sort

A slightly more unorthodox approach is to use .sort()

to sort the array in descending order in terms of its property a

, and then get the value of the first element b

, for example:

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

Run codeHide result


0


source


Try the following:

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

      

0


source







All Articles