Reputation: 116
var obj={'one':1,'two':50,'three':75,'four':12}
This is object from which i want the output as 'three':75, this is key value pair for maximum value in object. My constraint is not to use for loop and any library. Is it possible??
Upvotes: 3
Views: 768
Reputation: 1044
By the way I found another solution but it also uses loop.
var obj = {'one': 1, 'two': 50, 'three': 75, 'four': 12};
var maxKey = Object.keys(obj).sort(function (a, b) {
return obj[a] < obj[b];
})[0];
var result = {};
result[maxKey] = obj[maxKey];
Upvotes: 4
Reputation: 7117
you can make a new object form given object of this structure
var newObject = [
{ key: 'one', value: 1 }, // key value structure
{ key: 'two', value: 50 },
{ key: 'three', value: 75 },
{ key: 'four', value: 12 }
];
var obj = {
'one': 1,
'two': 50,
'three': 75,
'four': 12
}
var newObJ = Object.keys(obj).map(function (key) {
return {
"key": key,
"value": obj[key]
}
});
var max = Math.max.apply(null, newObJ.map(function (el) {
return el.value;
}));
var output = newObJ.filter(function (el) {
return el.value === max;
})[0];
document.write(output.key + ': ' + max);
Upvotes: 0
Reputation: 63524
You could perhaps achieve this if you were willing to change your data structure around a bit. Instead of an object have an array of objects, and then use filter
to grab the object based on the maximum value:
var arr = [
{ key: 'one', value: 1 },
{ key: 'two', value: 50 },
{ key: 'three', value: 75 },
{ key: 'four', value: 12 }
];
var max = Math.max.apply(null, arr.map(function (el) {
return el.value;
}));
var output = arr.filter(function (el) {
return el.value === max;
})[0];
console.log(out.key + ': ' + out.value); // three: 75
Upvotes: 1
Reputation: 1044
My solution with loop.
var obj = {'one':1,'two':50,'three':75,'four':12} ;
var maxKey = Object.keys(obj).reduce(function (prev, next){
return obj[prev] > obj[next] ? prev : next;
});
var result = {};
result[maxKey] = obj[maxKey];
console.log(result);
Upvotes: 2