I have to get highest keys with values in javascript object
var obj1 = {a: 1, b: 3, c: 2, d: 4};
var obj2 = {a: 1, b: 3, c: 2, d: 3};
I tried these codes code1
var max = Object.keys(r).reduce(function(a, b){ return r[a] > r[b] ? a : b });
code2
var max = _.max(Object.keys(obj), function (o) {return obj[o];});
code3
var max = Math.max.apply(null,Object.keys(obj).map(function(x){ return obj[x] }));
console.log(Object.keys(obj).filter(function(x){ return obj[x] == max; })[0]);
each code work ok in case of obj1, returns d because it's with max value 4 but in case of obj2 not return value according to my requirement it return only one key but I need all keys with highest values in case of obj2 requires the b & d because they both are highest value 4
Thanks Dinesh
You can do it like this using underscore.js
var obj1 = {
a: 2,
b: 3,
c: 2,
d: 4
};
var obj2 = {
a: 1,
b: 3,
c: 2,
d: 3
};
//get the max
n = _.max(obj2, function(o) {
return o;
})
//filter keys with max
j = _.filter(Object.keys(obj2), function(o) {
return obj2[o] == n
})
//use map to get the key and value in an array
result = j.map(function(d){ return {key:d, value:obj2[d]}})
console.log(result)
working code here
Another option using underscore chain here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.