1

How to compare between object elments values in javascript

For example :

var obj = { tom: "5000", justin: "500", linda: "3000" };

How I can make a code to know which person have the higher salary as in the example: I should get as a result here (tom)?

2 Answers 2

3

You could get first all keys of the object with Object.keys and then reduce by getting the higher salary key with Array#reduce.

var object = { tom: "5000", justin: "500", linda: "3000" },
    keys = Object.keys(object),
    max = keys.reduce(function (a, b) {
        return +object[a] > +object[b] ? a : b;
    });

console.log(max);

For getting more than only one top key, you need a different approach and return an array instead of a single value.

var object = { justin: "500", linda: "3000",  tom: "5000", jane: "5000" },
    keys = Object.keys(object),
    max = keys.reduce(function (r, a, i) {
        if (!i || +object[a] > +object[r[0]]) {
            return [a];
        }
        if (+object[a] === +object[r[0]]) {
            r.push(a);
        }
        return r;
    }, []);

console.log(max);

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

1 Comment

This will compare strings, not numbers. If my object would be something like { tom: "5000", justin: "500", linda: "3000", tim: "10000" }, it will produce an incorrect result. I suggest adding parseInt() to get a number from a string.
0
function getMaxUser(object) {
    let maxUser = { max: 0 }
    for (let user in object) {
        if (maxUser.max < object[user]) {
            maxUser = {
                max: object[user],
                user: user
            }
        }
    }
    return maxUser
}
var obj = { tom: "5000", justin: "500", linda: "3000" }
console.log(getMaxUser(object).user)  //tom

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.