jeffci
jeffci

Reputation: 2622

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 the lowest value, in this case it's {CICO: 1228}.

How I create this object is like so:

  let basic = [];

  _.map(values, value => {
    let result = value[Object.keys(value)].reduce((c, v) => {
      // sum up the amounts per key
      c[Object.keys(value)] = (c[Object.keys(value)] || 0) + parseInt(v.amount);
      return c;
    }, {});
    basic.push(result);
  }) 

  console.log(basic) => [{PINO: 1764}, {FANH: 2737}, {WQTR: 1268}, {CICO: 1228}]

How can I get the lowest number with it's key from the basic object? I tried using sort and taking the lowest number but the keys are created dynamically so I don't think I have anything I can sort against.

Upvotes: 0

Views: 62

Answers (2)

Mark
Mark

Reputation: 92440

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.

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 192016

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);

Upvotes: 1

Related Questions