最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Find maximum value of property in object of objects - Stack Overflow

programmeradmin1浏览0评论

I have an object like this:

const users = {
 adam: {
   age: 28,
   extraInfo: 'foobar',
 },
 brad: {
   age: 31,
   extraInfo: 'foobar',
 },
 jef: {
   age: 12,
   extraInfo: 'baarfoo',
 },
};

How can I check which object has the highest value of "age" property and get this object to a constant??

I've tried to use Object.keys(), throw data to Array and reduce but in the end, all these methods were not working as I wanted. I've been stuck on this issue for hours right now.

I have an object like this:

const users = {
 adam: {
   age: 28,
   extraInfo: 'foobar',
 },
 brad: {
   age: 31,
   extraInfo: 'foobar',
 },
 jef: {
   age: 12,
   extraInfo: 'baarfoo',
 },
};

How can I check which object has the highest value of "age" property and get this object to a constant??

I've tried to use Object.keys(), throw data to Array and reduce but in the end, all these methods were not working as I wanted. I've been stuck on this issue for hours right now.

Share Improve this question edited Dec 2, 2018 at 16:09 Rohan Dhar 1,8371 gold badge12 silver badges21 bronze badges asked Jan 30, 2018 at 18:05 p7adamsp7adams 6623 gold badges9 silver badges26 bronze badges 3
  • what should happen if you get two persons with same max age? – Nina Scholz Commented Jan 30, 2018 at 18:26
  • You can use _.maxBy – mpen Commented Jan 30, 2018 at 18:32
  • @mpen I can't use any external library. – p7adams Commented Jan 30, 2018 at 18:50
Add a ment  | 

3 Answers 3

Reset to default 6

You can use reduce function to find the object with the highest age.

Basically, the reduce function will loop the users object using its keys, and will be changing the accumulator according to the age value.

The "key" of this solution is:

const result = Object.keys(users). reduce((acc, curr) =>    
   acc.age ? (users[curr].age > acc.age ? users[curr] : acc) : users[curr], {});

How this works:

  • Object.keys(users): This function returns the array of keys from a specific object, in your case ["adam", "brad", "jef"].

  • The reduce function will loop the Array of keys and will keep an accumulator (Current highest age) and a currentValue (Current item from source Array Object.keys(users)).

  • acc.age ? (users[curr].age > acc.age ? users[curr] : acc) : users[curr], {}) that condition evaluates the current values of accumulator and currentValue

    • Ask for acc.age because the reduce function starts with an empty initialValue {}:

      Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error.

    • If acc.age has a previous value then this condition (users[curr].age > acc.age ? users[curr] : acc) : users[curr] makes the swap between accumulator and currentValue (Pick the highest age).

const users = {
  adam: {
    age: 28,
    extraInfo: 'foobar',
  },
  brad: {
    age: 31,
    extraInfo: 'foobar',
  },
  jef: {
    age: 12,
    extraInfo: 'baarfoo',
  },
};

const result = Object.keys(users).reduce((acc, curr) =>    
       acc.age ? (users[curr].age > acc.age ? users[curr] : acc) : users[curr], {});

console.log(result)

Solution suggested by @irkeninvader using for-loop:

const users = {
 adam: {
   age: 28,
   extraInfo: 'foobar',
 },
 brad: {
   age: 31,
   extraInfo: 'foobar',
 },
 jef: {
   age: 12,
   extraInfo: 'baarfoo',
 },
};

var maxAge;
for(var key in users){
  if(!maxAge || users[key].age > maxAge.age){
    maxAge = users[key];
  }
}

console.log('Highest Age is:');
console.log(maxAge);

You could take an array as result set for max age, because you could get more than one user with the same max age.

This proposal uses the keys of the object and iterates them and checks if the index is zero, or if the last result user has a smaller age than the actual user, then take a new array with the actual key as result.

If the age is equal, then append the actual user key to the result set. If not return the last result.

const
    users = { adam: { age: 28, extraInfo: 'foobar' }, brad: { age: 31, extraInfo: 'foobar' }, jef: { age: 12, extraInfo: 'baarfoo' } },
    maxAge = Object
        .keys(users)
        .reduce((r, k, i) => !i || users[r[0]].age < users[k].age
            ? [k]
            : users[r[0]].age === users[k].age
                ? r.concat(k)
                : r, []);

console.log(maxAge);

   Here is code to find highest age object but I am not sure whether you can assign the result to a constant

  function highestAge( ageArray ) {
      var highest = null;
      for ( var key in ageArray ) {
            var val = ageArray[key];
             if( highest != null ) {
                 if ( highest.age < val.age ) {
                      highest = val;
                 }
             } else {
                 highest = val;
             }
           }
           return highest;
     }
发布评论

评论列表(0)

  1. 暂无评论