Sorting Object Values with Alternate Order

Is there a way to sort a JSON response object array in a specific order, especially when dealing with non-English characters like Umlauts?

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

Expected name sorting would be A, Ä, and B.

Upon attempting to use localeCompare() for sorting:

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

An error is encountered stating that object.sort is not a function. Is there an alternate method to sort the object array?

Answer №1

In order to sort the object, you must utilize its properties.

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

Answer №2

Remember to always apply the sort() function to the array itself, not the surrounding object. Objects do not possess this method and key order is not guaranteed in general. It's best practice to use arrays for "ordered" data rather than objects!

In this instance, we are utilizing the o.users array. The resulting output n is also an array.

IMPORTANT: Avoid using reserved keywords as variable names. If you choose to use object as a variable name, it's highly advised not to do so! I've opted for o instead. While object isn't a reserved keyword, Object (with a capital O) is. These two can easily be mistaken for one another.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Confusion about the unwinding of the call stack in the Graph Depth-

Issue with function: hasPathDFSBroken Fix implemented in: hasPathDFS The updated version includes a forced parameter to address the issue, which I would prefer to avoid. I'm trying to comprehend why in the broken version, when the call stack unwinds ...

What is the correct way to establish and terminate a MongoDB connection in a Node.js application?

Hey everyone, I have a piece of code at this link (https://github.com/MrRav3n/Angular-Marketplace/blob/master/server.js) and I'm curious if I am properly starting and ending my database connection. Should I connect and end the db connection in every a ...

What could be the reason for this XSS script not making a request to my server?

Currently diving into the realm of XSS attacks to enhance my knowledge on application security. My goal is to extract the user's cookie from a local website and then transmit it to my local server for testing purposes. I've successfully obtained ...

Trying to access a property that doesn't exist (fetching 'fetchBans')

My goal is to create a command within my Discord bot that can unban a user. However, when I finished writing the code, I encountered an error stating 'Cannot read properties of undefined (reading 'fetchBans'). Here is the section of code cau ...

How can we eliminate the 'www' in a URL using NodeJS and Express?

What is the best way to eliminate the 'www' in a URL using NodeJS + Express? For instance, when a client connects to , how can we automatically redirect them to without the 'www'? ...

Ways to modify the default text in a dropdown menu?

I'm currently attempting to modify the title of a dropdown using the Multi-select plugin found here. However, I've encountered an issue where I am unable to dynamically change the text (Dropdown title) of the dropdown using JavaScript. $(' ...

Searching for documents in MongoDB that meet specific criteria has become possible through the use

Criteria: COUNT the total number of documents in the collection WHERE objects.objectType is 'group' AND (objects.objectType is NOT 'person' AND relation is 'Exposed_to') Expectation: should return the count of all documents W ...

What causes compatibility issues between JEST and import statements in NEXTJS?

Just starting out with unit testing in JavaScript and I'm attempting to create a unit test for a Next JS project. However, when running the test, I encountered the following error: Code: import {isBase64} from '../../service/base64-service&a ...

Customizing the Slider Range with HTML DOM Style's BackgroundImage Attribute

I have a slider range that I'd like to modify using JavaScript. Specifically, I want to change its background-image property. To achieve this, I attempted the following script: document.getElementById("range").style.backgroundImage = "linear-gradient ...

Error occurred in Flask due to request names being dynamically generated using JavaScript

My current project involves creating an app that calculates transit projections based on input years and other variables. I've written a JavaScript script where users can add new types of vehicles, each generating a unique div with specific ids and na ...

The Express API is failing to recognize the data keys that were sent from the React frontend, despite being clearly specified

I am facing an issue while trying to send data to a REST API using React hosted in a separate application. The API does not seem to receive the keys sent, even though I checked the results in Chrome and found this output:(2) ["imageSrc", File]0: "imageSrc" ...

AngularJS uiSortable - visually indicating the movement of a table cell when dragging an item with the mouse

Utilizing uiSortable (uiSortable) within my application has been quite successful. However, I have encountered an issue where I am unable to highlight the drop cell before actually dropping the item into it. Below is a snippet of my HTML code: <td ui-s ...

creating a distinct angular service for every controller

Lately, I've been utilizing Angular services to store my commonly used codes that are required across different parts of my project. However, I have encountered an issue where variables in the service are shared between controllers. This means that if ...

Error: When attempting to utilize the Image-Slider, an issue arises with reading the property 'classList' which is undefined

I am currently in the process of developing a website using Strapi as my CMS and Next.js(React) for the frontend. The website features an image slider that includes images, headlines, and descriptions. However, I have encountered an issue where after spen ...

Tips for eliminating empty trailing values and Carriage Returns from a JavaScript array

I needed a way to eliminate empty elements and Carriage Returns from the end of an array. Here's an example of what my array looks like: Input arr: ['', 'Apple', '', 'Banana', '', 'Guava', & ...

Employing ng-click within a displayed column of Datatable

Currently, I am utilizing a plain Datatable in AngularJS without any Angular-Datatable libraries. Everything appears to be working well except for one issue. Here is the datatable code snippet: $scope.siInfoTable = $('#siInfoTable').DataTable({ ...

What is the most effective way to access content from a webpage that is rendered

Is there a reliable way to download from links on a JavaScript rendered webpage using Python as the preferred language? I have attempted to use the Selenium Python bindings on a headless server, but it has proven to be slow, error-prone, and unable to acc ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

Express Producing Empty Axios Post Request Body

I am facing an issue with sending two text data pieces from my React frontend to an Express backend. Whenever I use the post command with Axios, the body appears as {} in the backend and becomes unusable. Below is the code that I am using. Client (App.js) ...

I am getting a HTTP 405 error indicating that the method is not allowed, and it appears to

In my Javascript program, I requested this URL using the library epson-2.6.0.js, which is the Epson SDK for JavaScript specifically designed for thermal printers. My target device is a TM U220 connected via ethernet. GET XHR http://192.168.199.15:8008/soc ...