I need to find extreme values in an object with given average number but honestly I have no idea how to approach to this problem. so I have an object and average with values like that:
const avg = 0.5;
const myjson = {
'key1': 0.5,
'key2': 0.8,
'key3': 0.3,
'key4': 0.2,
'key5': 0.5,
};
So basically average is 0.5, and I wish to get biggest extremes, in above example it would be 'key2' and 'key4'.
so the output should look like this:
const reducedJson = {
'key2': 0.8,
'key4': 0.2,
}
Also in case if there is 3 exteme values, for example there would be 'key6': 0.2, I should return three extremes because two are same.
Sorry that no my code attempts but as I said, I need some help or tip at least because I don't know how to start...
CodePudding user response:
you can do something like this
const myjson = {
'key1': 0.5,
'key2': 0.8,
'key3': 0.3,
'key4': 0.2,
'key5': 0.5,
};
const extractExtreme = data => {
const min = Math.min(...Object.values(data))
const max = Math.max(...Object.values(data))
return Object.fromEntries(Object.entries(data).filter(([k, v]) => v === max || v === min))
}
console.log(extractExtreme(myjson))
CodePudding user response:
You seem to make things harder than it is. The average has nothing to do with the min/max... Simply loop over the values, if you find a value lower/bigger than the lowest/biggest you had, keep this one instead and save the key.
const avg = 0.5;
const myjson = {
'key1': 0.5,
'key2': 0.8,
'key3': 0.3,
'key4': 0.2,
'key5': 0.5,
};
let lowest = Infinity;
const lowestKeys = [];
for(const key in myjson){
if(myjson[key]<lowest){
lowestKeys.length = 0;
lowestKeys.push(key);
lowest = myjson[key];
}elseif(myjson[key]==lowest){
lowestKeys.push(key);
}
}
You can then do another loop for the max, or fit it in the same loop... The logic will be the same but instead of looking for lower, you'd look for higher.