I have managed to identify the highest number out of the count properties however I want to log the object associated with that number, ie log the object with the highest count number. How do I do this?
var objects = {
object1: {username: 'mark', count: 3},
object2: {username: 'dave', count: 5},
object3: {username: 'lucy', count: 2},
};
var maxBap = Math.max.apply(Math,objects.map(function(o){return o.count;}));
console.log(maxBap);
Thanks
Instead of .map()
, use .reduce()
to get the desired target.
Here I'm returning the key of the result object. You could return the object directly if you wish.
var objects = { object1: {username: 'mark', count: 3}, object2: {username: 'dave', count: 5}, object3: {username: 'lucy', count: 2}, }; var res = Object.keys(objects).reduce(function(resKey, key) { return objects[resKey].count > objects[key].count ? resKey : key }) document.querySelector("pre").textContent = res + ": " + JSON.stringify(objects[res], null, 4);
<pre></pre>
If objects
was meant to be an Array, you can still use .reduce()
, just without Object.keys()
. This returns the objects directly, which was alluded to in the first solution.
var objects = [ {username: 'mark', count: 3}, {username: 'dave', count: 5}, {username: 'lucy', count: 2}, ]; var res = objects.reduce(function(resObj, obj) { return resObj.count > obj.count ? resObj : obj }) document.querySelector("pre").textContent = JSON.stringify(res, null, 4);
<pre></pre>
You could use .reduce
instead of .map
.
const objects = [
{ username: 'mark', count: 3 },
{ username: 'dave', count: 5 },
{ username: 'lucy', count: 2 },
]
const max = objects.reduce((acc, obj) => (
obj.count > acc.count ? obj : acc
))
console.log(max)
You can first find max
of count and then find object with that count
var objects = { object1: {username: 'mark', count: 3}, object2: {username: 'dave', count: 5}, object3: {username: 'lucy', count: 2}, }, result = null; var max = Math.max.apply(null, Object.keys(objects).map(e => {return objects[e].count})); for (var obj in objects) { if (objects[obj].count == max) result = objects[obj]; } console.log(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.