Search code examples
javascriptloopsobjectfor-in-loop

How to compare elements in an object and return the higher value? *Javascript*


I am trying to compare two elements inside an object in Javascript. The letter that has the highest value, should be returned along with the number it carries.

This is the object and we should return a and 39.

obj({a:39,b:21,c:12,d:4}) // should return a : 39

Here is my code so far.

let obj = object => {

  for(let i in object) { // i  represents the "key" of the objects, a,b,c,d
    if(object[i] > object[i + 1]) { // object[i] represents the "value" held 39,21,12,4
      console.log(i + ":" + object[i]);
    } else {
      console.log(i + ":" + object[i]);
    }
  }
}

obj({a:39,b:21,c:12,d:4})

I thought object[i + 1] in the if statement would compare the next indexed element to the current one but it doesn't, how would you accomplish this?

EDIT if there are two elements with the same value then return both of the elements

This is probably the easiest way to accomplish this for people new to coding like me. This code returns the highest number held in the object.

let getMax = (obj) => {
  let highestValue = 0;
  for(var i in obj) {
    if(highestValue < obj[i]) {
      highestValue = obj[i];
    } else if (highestValue == obj[i]) {
      highestValue = highestValue + " " + obj[i];
    }
  }
  alert(highestValue);
}
getMax({John:300000,Kary:360000,David:2700000,Michelle:2700000})

Solution

  • On each iteration check if the current or previous key value is the largest, and store. Store the largest in the largest variable. In the end return the largest variable, and it's value (object[largest]):

    let obj = object => {
      let largest;
      for(const i in object) { // i  represents the "key" of the objects, a,b,c,d
        if(!largest || object[i] > object[largest]) {
          largest = i;
        }
      }
      
      return { [largest]: object[largest] };
    }
    
    console.log(obj({a:39,b:21,c:12,d:4}));

    Suggested solution:

    Use Object.entries() to get key|value pairs. Iterate with Array.reduce(), choose the pair with the highest value (index 1). Destructure the reduce's result (an array with [key, value]) into key and value consts, and use them to build the return object.

    const obj = (object) => {
      const [key, value] = Object.entries(object)
        .reduce((r, e) => e[1] > r[1] ? e : r);
      return { [key]: value };
    };
      
    console.log(obj({a:39,b:21,c:12,d:4}));