I am attempting to create a function that takes an object and returns an array with the highest and lowest keys. My problem is the array does not have the highest value but instead the second highest value? My code is below and even when I add a second while value (another loop for max) it still comes up with the second highest value.
function minMaxKeyInObject(obj) {
let newArr = [];
let min;
let max;
for (let i in obj) {
if (min === undefined || i < min) {
min = i;
}
if (i > max){
max = i;
}
}
for (let j in obj) {
// console.log(j)
if (max === undefined || j > max) {
max = j;
}
}
newArr.unshift(max);
newArr.unshift(min);
return newArr;
}
let obj = { 1: 'Max', 2: 'Jim', 4: 'Leia', 11: 'Jacob', 7: 'Bob', 8: 'Kim', 3: 'Billy' }
I am having zero issues with the min value it's just the max.
I have tried changing the conditional, adding in a second conditional, a second loop, and switching the order but the results stay the same. Any help would be appreciated.