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}
1

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

2 Comments

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 - If you want order, yes, use an array. I've added an example to the end of one way you might do it.

Your Answer

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.