1

I have been trying to sort the json response object array in specific order like if the object contains Umlaute words/characters

object {
  item: 1,
  users: [
   {name: "A", age: "23"}, 
   {name: "B", age: "24"},
   {name: "Ä", age: "27"}
 ]
}

Expected name sorting is A, Ä and B.

when trying to sort with localecompare().

object.sort(function (a, b) { return a.localeCompare(b); });

Getting the error like object.sort is not a function. Is there anyway to sort the object array.

6
  • no you cannot do that. sort is an array method and you can never guarantee the order of object keys Commented Jan 2, 2019 at 14:17
  • I understand but any alternative for it? Commented Jan 2, 2019 at 14:19
  • Looking at your example, You do have an array of objects and it is possible to sort this array using sort. Shouldn't you do object.users.sort((a,b) => a.name.localeCompare(b.name)). Commented Jan 2, 2019 at 14:21
  • I have tried object.users.sort((a,b) => a.name.localeCompare(b.name)) but throws an error like a.localeCompare is not a function Commented Jan 2, 2019 at 14:23
  • it's a.name.localeCompare(b.name)) not a.localeCompare(b.name)) Commented Jan 2, 2019 at 14:28

2 Answers 2

2

You need to take the property of the object for sorting.

var object = { item: 1, users: [{ name: "A", age: "23" }, { name: "B", age: "24" }, { name: "Ä", age: "27" }] };

object.users.sort(function (a, b) { return a.name.localeCompare(b.name); });

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

3 Comments

how do you know he want to sort the user?
@brk, "Expected name sorting is A, Ä and B. ".
@klmuralimohan, does the above works for you? do you use a.localeCompare? a is an object, not a string, like name.
0

You must apply the sort() function to the array, not the outer object. Objects don't have that method and in the general case key order is not guaranteed, anyways. For "ordered" data always use arrays, not objects!

This is an example that uses the o.users array. The output n is also an array.

NOTE: never abuse reserved keywords as variable names. You use object as a variable name, it is strongly recommended to not do so! I've replaced it with o. Albeit object is not a reserved keyword, Object (with capital O) is. And the two are easily confused.

var o = {
  "item": 1,
  "users": [
    { "name": "A", "age": "23" },
    { "name": "B", "age": "24" },
    { "name": "Ä", "age": "27" }
  ]
};

var n = o.users.sort((a, b) => a.name.localeCompare(b.name, "de"));

console.log(n);

Comments

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.