-2

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...

pilchard
  • 12,414
  • 5
  • 11
  • 23
Jacki
  • 632
  • 3
  • 14
  • 26
  • 1
    `myjson` is not a JSON formatted string - it is a JavaScript object. Please remove any references to JSON in the question! – phuzi Jun 30 '22 at 08:05
  • 1
    Does this answer your question? [Fast way to get the min/max values among properties of object](https://stackoverflow.com/questions/11142884/fast-way-to-get-the-min-max-values-among-properties-of-object) – pilchard Jun 30 '22 at 08:18

2 Answers2

2

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))
R4ncid
  • 6,944
  • 1
  • 4
  • 18
2

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.

Salketer
  • 14,263
  • 2
  • 30
  • 58