Javascript expected object result not getting when sorting on value numbers( and both key and value are also numbers)
let team_id_Point = {
26: 15,
32: 1,
127: 21,
};
function sortObjectbyValue(obj = {}, asc = true) {
const ret = {};
Object.keys(obj)
.sort((a, b) => obj[asc ? a : b] - obj[asc ? b : a])
.forEach((s) => (ret[s] = obj[s]));
return JSON.stringify(ret);
}
console.log(sortObjectbyValue(team_id_Point, false));
result from above:
{"26":15,"32":1,"127":21}
required output:
{"127":21,"26":15,"32":1}
CodePudding user response:
Although JavaScript object properties have an order now, relying on their order is an antipattern.
If you need order, use an array.
required output
You cannot get the required output with a JavaScript object, because:
- Those property names are array index names, and so the object's "order" puts them in order numerically.
JSON.stringify
follows the property order of the object.
Also note that JSON (as distinct from JavaScript) considers objects "...an unordered set of name/value pairs..." So to JSON, {"a": 1, "b": 2}
and {"b": 2, "a": 1}
are exactly equivalent.
You could use a Map
, but then the JSON representation wouldn't be what you're expecting.
Or you could build the JSON manually (ignoring that JSON doesn't consider objets to have any order), using JSON.stringify
for the values but outputting the {
, property names, and }
yourself.
But really, if you need order, use an array.
Here's an example using an array of arrays:
let team_id_Point = [
[26, 15],
[32, 1],
[127, 21],
];
function sortTeamIdPoint(data = [], asc = true) {
const result = [...data];
const sign = asc ? 1 : -1;
result.sort((a, b) => (a[0] - b[0]) * sign);
return JSON.stringify(result);
}
console.log(sortTeamIdPoint(team_id_Point, false));
Or an array of objects:
let team_id_Point = [
{id: 26, points: 15},
{id: 32, points: 1},
{id: 127, points: 21},
];
function sortTeamIdPoint(data = [], asc = true) {
const result = [...data];
const sign = asc ? 1 : -1;
result.sort((a, b) => (a.id - b.id) * sign);
return JSON.stringify(result);
}
console.log(sortTeamIdPoint(team_id_Point, false));