0

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}
Ammar
  • 765
  • 1
  • 8
  • 18

1 Answers1

4

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));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • It means I should have to go with an array when doing sorting objects, whether it's a number key or a string key. am I right? – Ammar Apr 30 '22 at 12:11
  • @Ammar - If you want order, yes, use an array. I've added an example to the end of **one** way you might do it. – T.J. Crowder Apr 30 '22 at 12:17