Reputation:
I First must tell that i browsed the site here to find an answer but i couldn't.
I have an object which holds a key(service Name) and a value(counter), i want to extract from this object only the Max and Min value, and their keys.
an example:
Object {
"Learn JavaScript": 3, //Max
"Learn React": 2, //Ignore
"manicure": 1, //Min
}
and then i would like to create an array of objects which will hold them in desecending order
code i used to display the upper outcome:
const arrayofServices = services; //services => state the holding the services
const servicesCounter = arrayofServices.reduce((counterObj, service) => {
if (counterObj.hasOwnProperty(service)) {
counterObj[service] += 1;
return counterObj;
}
return {
...counterObj,
[service]: 1
};
}, {});
console.log("Service Counter in =>" ,servicesCounter);
any suggestions?
Upvotes: 0
Views: 1007
Reputation: 402
One more try :)
const obj = {"Learn JavaScript": 3, "Learn React": 2, "manicure": 1};
function MinMaxFromObj(obj) {
const min = Math.min(...Object.values(obj));
const max = Math.max(...Object.values(obj));
const minKey = Object.entries(obj).find(([key, value]) =>
value === min ? key : null);
const maxKey = Object.entries(obj).find(([key, value]) =>
value === max ? key : null);
return [Object.fromEntries([minKey]), Object.fromEntries([maxKey])];
}
console.log(MinMaxFromObj(obj));
Upvotes: 1
Reputation:
Here is an approach which can help you to solve your problem:
const minMaxEntry = (object) => {
let minKey;
let minValue = Infinity;
let maxKey;
let maxValue = -Infinity;
for (const key in object) {
if (object[key] < minValue) {
minKey = key;
minValue = object[key];
}
if (object[key] > maxValue) {
maxKey = key;
maxValue = object[key];
}
}
const minEntry = { [minKey]: minValue };
const maxEntry = { [maxKey]: maxValue };
return [minEntry, maxEntry];
};
// --- //
const object = {
"Learn JavaScript": 3,
"Learn React": 2,
"manicure": 1,
};
const [minEntry, maxEntry] = minMaxEntry(object);
console.log('Min Entry =>', minEntry);
// { "manicure": 1 }
console.log('Max Entry =>', maxEntry);
// { "Learn JavaScript": 3 }
Upvotes: 0