Skip to content Skip to sidebar Skip to footer

Taking The Lowest Number From A List Of Objects That Have Dynamic Keys

I am creating an object with dynamic keys as seen here: const myObject = [ {PINO: 1764}, {FANH: 2737}, {WQTR: 1268}, {CICO: 1228} ]; I want to get the key and value with t

Solution 1:

This is a pretty inconvenient way to store data since the keys are more-or-less useless and you need to look at the values of each object to do anything. But you can do it if you need to with something like:

const myObject = [
    {PINO: 1764},
    {FANH: 2737},
    {WQTR: 1268},
    {CICO: 1228}
  ];

let least = myObject.reduce((least, current) => Object.values(least)[0] < Object.values(current)[0] ? least : current)
console.log(least)

If it was a large list, you might benefit from converting the array to a different format so you don't need to keep creating the Object.values array.


Solution 2:

Iterate the array with Array.reduce(), get the values of the objects via Object.values(), and take the one with the lower number:

const myObject = [
  {PINO: 1764},
  {FANH: 2737},
  {WQTR: 1268},
  {CICO: 1228}
];

const result = myObject.reduce((r, o) => 
  Object.values(o)[0] < Object.values(r)[0] ? o : r
);

console.log(result);

Post a Comment for "Taking The Lowest Number From A List Of Objects That Have Dynamic Keys"