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
35.4k9 gold badges65 silver badges88 bronze badges
asked Feb 27, 2019 at 8:29
3
  • yea type of this seems to be like object ,, but thats the response i receive by api Commented Feb 27, 2019 at 8:31
  • Is this a text response? Like, is the API sending this exact string of characters? If so, the first order of business is to manually parse it into an actual array / object. Commented Feb 27, 2019 at 8:32
  • hi , i edited my question , please remove the downvote , thank you Commented Feb 27, 2019 at 8:36

2 Answers 2

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?

answered Feb 27, 2019 at 8:46
0
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

answered Feb 27, 2019 at 8:34
2
  • hi , this sorts only key , i need it with value too Commented Feb 27, 2019 at 8:54
  • yeah well, you can use it to generate a new sorted obj, i didnt know it was a big of a deal Commented Feb 27, 2019 at 10:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.