Reputation: 13
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)?
Upvotes: 1
Views: 91
Reputation: 386883
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);
Upvotes: 3
Reputation: 408
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
Upvotes: 0