2

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

@Cyrill thanks for help, but on my local pc your 1st return error Uncaught ReferenceError: _ is not defined at line "n = _.max(obj2, function(o) {" and same error in code 2 at "n = _.max(obj2, function(o) {" and I only need key like ['b', 'd']
can I do with jquery & what about need only key
This is pure javascript jsfiddle.net/cyril123/kzf5s4ry it will run anywhere without dependencies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.