Skip to content Skip to sidebar Skip to footer

Find Maximum Value Of Property In Object Of Objects

I have an object like this: const users = { adam: { age: 28, extraInfo: 'foobar', }, brad: { age: 31, extraInfo: 'foobar', }, jef: { age: 12, extraInfo: 'ba

Solution 1:

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);

Solution 2:

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);

Solution 3:

   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 ) {
            varval = ageArray[key];
             if( highest != null ) {
                 if ( highest.age < val.age ) {
                      highest = val;
                 }
             } else {
                 highest = val;
             }
           }
           return highest;
     }

Post a Comment for "Find Maximum Value Of Property In Object Of Objects"