1

I am receiving weird response from 3rd party api , that looks like below

{
  "27000CE": -1,
  "27100CE": 2,
  "27300CE": -1,
  "27200CE": 5
}

How do I sort this by value ?

like ascending or descending.

{
  "27300CE": -1,
  "27000CE": -1,
  "27100CE": 2,
  "27200CE": 5
}

I tried something like below

sortArrayOfObjects = (arr, key) => {
    return arr.sort((a, b) => {
        return a[key] - b[key];
    });
};

But all keys are different and thats the problem.

adiga
  • 34,372
  • 9
  • 61
  • 83
Gracie williams
  • 1,287
  • 2
  • 16
  • 39

2 Answers2

1

You can sort the Object.entries and then create a new object using reduce like this:

const response = {
  "27100CE": 2,
  "27000CE": -1,
  "27300CE": -1,
  "27200CE": 5
}

const sorted = Object.entries(response)
                         .sort((a, b) => a[1] - b[1])
                         .reduce((r, [key, value]) => {
                            r[key] = value
                            return r
                         }, {})

console.log(sorted)

This works only if you don't have any integer keys in response. More info: Does JavaScript Guarantee Object Property Order?

adiga
  • 34,372
  • 9
  • 61
  • 83
0

I believe you receive an object, in that case your input will be like this:

let obj = {"27300CE": -1, "27200CE": 5, "27100CE": 2, "27000CE": -1}

And you can sort by values like so:

let keys = Object.keys(obj);

// Then sort by using the keys to lookup the values in the original object:
keys.sort(function(a, b) { return obj[a] - obj[b] });

console.log(keys);//["27300CE", "27000CE", "27100CE", "27200CE"]

based upon new keys sequence you can create a new obj , sorted one if you like

Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64