Reputation: 79
I am having an object {1:2, 2:1}. The first one is the key and second one is the value. I want to know which one is height. From the example first one has the highest value.
How can i find it using jquery or js.
My expected output should be 1 is highest,
if {1:1, 2:2 } then 2 is highest.
if {1:3} then 1 is highest.
if {2:3} then 2 is highest.
Upvotes: 1
Views: 137
Reputation: 10282
let obj = {1:2, 2:1, 3:55, 4:1, 5:60};
let highest = Object.keys(obj).reduce(function(a, b){ return obj[a] > obj[b] ? a : b });
console.log(highest);
Upvotes: 0
Reputation: 2791
You can also find it with for
loop by iterating each property of an object.
var obj = {
"1": 1,
"2": 3,
"3": 7,
"4": 6
},
result, final;
for (var key in obj) {
if (result == undefined) {
result = obj[key];
final = key;
} else {
if (obj[key] > result) {
result = obj[key];
final = key;
}
}
}
console.log(final);
Upvotes: 0
Reputation: 89
let object = {
1:10,
2:2,
12:30,
15:4
};
// Returns array of a given object's property names
let key = Object.keys(object)
// Compare each value
.reduce((a, b) => object[a] > object[b] ? a : b);
Upvotes: 0
Reputation: 28475
Try following
let obj = {1:2, 2:1};
let result, temp;
Object.entries(obj).forEach(([k,v], i) => {
if (i === 0 || v >= temp) {result = k; temp = v;}
});
console.log(result);
Upvotes: 3
Reputation: 386868
You could reduce the entries and return the pair with the highest key/value pair and take the key only.
var object = { 1: 2, 3: 3, 5: 2, 6: 7 },
highest = Object.entries(object).reduce((a, b) => a[1] > b[1] ? a : b)[0];
console.log(highest);
Upvotes: 6