0

I'm stuck on why my Javascript findMaxObjectValue function will not work. Here's what I've come up with:

function findMaxObjectValue(obj) {
    return Object.keys(obj).reduce(function(a, b) {
        return (obj.a > obj.b) ? a : b;
    }, obj[a]);
}

When I run this:

findMaxObjectValue([{Alex: 1}, {Katie: 2}, {Nora: 3}, {Dana: 4}]) 

It returns '3', when I am hoping for '4'... All help appreciated!

2 Answers 2

1

It's because you are reducing the keys and not the values. It is comparing Alex, Katie, Nora and Dana. Nora comes last lexicographically, so that is the answer.

If you want to sort by the values 1, 2, 3, 4, then use the values() method, not the keys() method.

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

Comments

0

Use Object.values instead of Object.keys

function findMaxObjectValue(obj) {

  var objLargestVal = Object.values(obj).reduce(function(a, b) {
    return (obj[a] > obj[b]) ? a : b;
  });
  for (var keys in objLargestVal) {
    return objLargestVal[keys]
  }
}


console.log(findMaxObjectValue([{
  Alex: 1
}, {
  Katie: 2
}, {
  Nora: 3
}, {
  Dana: 4
}]))

Comments

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.