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 }
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;
}
CodePudding user response:
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);
CodePudding user response:
You can use Object.entries combined with reduce and in cumulator keep object with maxKey and maxValue;
const data = { '4': 1, '6': 1, '7': 1, '8': 1, '10': 2, '12': 3 };
const max = Object.entries(data).reduce(({maxKey, maxValue = -Infinity}, [key, value]) => {
if(value > maxValue){
maxValue = value;
maxKey = key;
}
return {maxKey, maxValue}
}, {});
console.log(max);