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.
-
yea type of this seems to be like object ,, but thats the response i receive by apiGracie williams– Gracie williams2019年02月27日 08:31:51 +00:00Commented 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.user5734311– user57343112019年02月27日 08:32:19 +00:00Commented Feb 27, 2019 at 8:32
-
hi , i edited my question , please remove the downvote , thank youGracie williams– Gracie williams2019年02月27日 08:36:24 +00:00Commented Feb 27, 2019 at 8:36
2 Answers 2
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?
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
-
hi , this sorts only key , i need it with value tooGracie williams– Gracie williams2019年02月27日 08:54:42 +00:00Commented 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 dealAbhay Maurya– Abhay Maurya2019年02月27日 10:14:24 +00:00Commented Feb 27, 2019 at 10:14