JS: Find Largest Number In Array Of Objects
What's the easiest way to find the largest number in an array of objects and return that object? var arr = [ { num: 0.5 }, { num: 1 }, { num: 0.35 }] Tried to use forEach but coul
Solution 1:
reduce will do the job:
var maxObj = arr.reduce(function(max, obj) {
return obj.num > max.num? obj : max;
});
Solution 2:
returns the object with the largest number:
var arr = [ { num: 0.5 }, { num: 1 }, { num: 0.35 }]
var res = Math.max.apply(Math,arr.map(function(o){return o.num;}))
var obj = arr.find(function(o){ return o.num == res; })
console.log(obj);
Solution 3:
You could use lodash?
var arr = [ { num: 0.5 }, { num: 1 }, { num: 0.35 }]
var max = _.max(arr, function(item) {
return item.num;
});
per aquinas suggestion - switched _.sortBy with _.max (there is no _.maxBy anymore) plunkr: https://plnkr.co/edit/TYIou2GUUxRWcXoCXHnv?p=preview
Solution 4:
Try using Math.max()
, JSON.stringify()
, String.prototype.match()
var arr = [ { num: 0.5 }, { num: 1 }, { num: 0.35 }];
var res = arr[(m = Math.max.apply(Math, n = JSON.stringify(arr).match(/(\d+\.\d+)|(\d+)/g))) && n.indexOf(m+"")];
Post a Comment for "JS: Find Largest Number In Array Of Objects"