Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using for in to iterate through objects values and return the highest value – Can I use it in the same way I would a for Loop

I am trying to return the mode of a passed array. I have read a lot about for in loops but due to es6 syntax used in these examples, I am struggling to understand how I can use this loop. My question: I want to return the key that has the highest value of all the object pairs.

I.e with the following object:

{ '4': 1, '6': 1, '7': 1, '8': 1, '10': 2, '12': 3 }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to return the key that contains the highest value. In this case it would be 12 since 3 is the highest value out of the pairs.

Is it possible to use a for in loop in a similar way to how I would iterate through an array to find the highest value. (I understand that non-array objects are not indexed in the same way arrays are, but I need to compare one key:value pair to the next in the loop and not sure how to code that). I.e:


let highest = 0;
      for(const x in count){
        if(count[x+1] > count[x]){
         highest = count[x][i+1];
       }

When I pass the code below it returns 0 so I assume the For In loop isn’t working as expected.

Full Code for reference:


function highestRank(arr){
  
  const count = {};
  
  for(let i=0; i<arr.length; i++){
    if(count.hasOwnProperty(arr[i]) === false){
        count[arr[i]]= 1;
      }else{
        count[arr[i]] += 1;
      }
  }
 //code below is the issue
  let highest = 0;
  for(const x in count){
    if(count[x+1] > count[x]){
     highest = count[x][i+1];
   }
  } 
  
  return highest;
}

>Solution :

Traditional loop version, use variables greatest and its respective key, loop the object properties

const count = { '4': 1, '6': 1, '7': 1, '8': 1, '10': 2, '12': 3 };

let greatest = -Infinity;
let key;
for (let x in count) {
  if (count[x] > greatest) {
    key = x;
    greatest = count[key];
  }
}

console.log(key, greatest);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading