Arranging a JSON Object Array in JavaScript by its alphanumeric key attribute order

I need assistance sorting this JSON array by unitId

var array = [
{ id: 10, unitId: 'unit17' }, 
{ id: 11, unitId: 'unit19' },
{ id: 13, unitId: 'unit27' }, 
{ id: 12, unitId: 'unit2' }, 
{ id: 13, unitId: 'unit11' },
{ id: 14, unitId: 'unit1'}
];

I am looking for the output array to be arranged as follows

var array = [
{ id: 14, unitId: 'unit1' }, 
{ id: 12, unitId: 'unit2' }, 
{ id: 13, unitId: 'unit11' }, 
{ id: 10, unitId: 'unit17' },
{ id: 11, unitId: 'unit19'},
{ id: 13, unitId: 'unit27' }
];

Answer №1

If you want to arrange the elements in a given array based on their alphanumeric unitId, you can achieve this by utilizing the sort() method along with a custom comparator function. Below is an illustration:

var array = [
  { id: 10, unitId: 'unit17' },
  { id: 11, unitId: 'unit19' },
  { id: 13, unitId: 'unit27' },
  { id: 12, unitId: 'unit2' },
  { id: 13, unitId: 'unit11' },
  { id: 14, unitId: 'unit1' }
];

array.sort((a, b) => {
  const unitIdA = parseInt(a.unitId.replace('unit', ''), 10);
  const unitIdB = parseInt(b.unitId.replace('unit', ''), 10);
  return unitIdA - unitIdB;
});
    
console.log(array);

The result will be the correctly sorted array:

[
  { id: 14, unitId: 'unit1' },
  { id: 12, unitId: 'unit2' },
  { id: 13, unitId: 'unit11' },
  { id: 10, unitId: 'unit17' },
  { id: 11, unitId: 'unit19' },
  { id: 13, unitId: 'unit27' }
]

When using the sort() function, it requires a customized comparator to compare elements a and b. The unitId values are first cleaned of the 'unit' string and then converted to integers through parseInt(). Subsequently, the difference between the unitId integers defines the sorting sequence.

Answer №2

One method to sort an array based on a specific property is by using regex to remove non-digit characters and then comparing the results.

var array = [
{ id: 10, unitId: 'unit17' }, 
{ id: 11, unitId: 'unit19' },
{ id: 13, unitId: 'unit27' }, 
{ id: 12, unitId: 'unit2' }, 
{ id: 13, unitId: 'unit11' },
{ id: 14, unitId: 'unit1'}
];

let sorted = array.sort((a,b) => a.unitId.replace(/\D/g,'') - b.unitId.replace(/\D/g,''))

console.log(sorted)

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

Troubleshooting issue: Angular not resolving controller dependency in nested route when used with requirejs

When the routes are multiple levels, such as http://www.example.com/profile/view, the RequireJS is failing to resolve dependencies properly. However, if the route is just http://www.example.com/view, the controller dependency is resolved correctly. Below ...

Issues with response functionality in Node.js (Openshift) using express

I am currently working with OpenShift and Node.js to calculate the average rating for each result. However, I am facing an issue where the response is not being displayed even though the console logs show the correct data. The console displays 3.9454323, ...

Is anyone else experiencing issues with loading a font from a CDN? It works perfectly fine on Chrome Browser and Safari for iOS Simulator, but for some reason, it's not loading

It's driving me a bit crazy as I'm not sure where I've gone wrong. I'm currently working with NextJS and have loaded this font into my <Link />. While it displays perfectly on Chrome and Safari in the iOS simulator, it fails to l ...

"Python's ability to dynamically update and print multiple lines in real-time

As a newcomer to Python, I am faced with a challenge that I cannot seem to crack. My Objective: I am seeking a method to dynamically update and display output on multiple lines within the console. While there are numerous solutions available for single-l ...

Tips for validating Angular form group input depending on the value of another input within the form?

I am facing an issue with form validation in my Angular version 8 application. I need to validate a form based on the following rules: If a file is uploaded (even if just clicking the button without selecting a file), then the Reason input is not required ...

Several mistakes occurred involving auth0, react, apollo, babel, and webpack

I seem to be facing some challenges while trying to integrate auth0 into my project. Every time I fix one issue, another one pops up and it's always the same trio of errors: -require is not a function -window is not defined -missing class properties ...

When a new marker is clicked on Google Maps, the previous Infowindow will automatically close

Here are some specific locations to consider: var places = [{ "id": 1, "ReferenceNumber": "52525252525", "Address" : "School" , "Latitude": "21.585486", "Longitude": & ...

Encountering silence: React JS fetch call left unanswered by Sinatra server

Exploring the realms of Sinatra and React JS, I am venturing into making a GET call from my React website to a Sinatra server in order to display plain text. The Sinatra Server script: require 'sinatra' set :root, 'lib/app' before d ...

What is the best way to prioritize a non-submit button over a submit button in material-ui?

I am facing an issue with a form on my website. Whenever I press the enter key, the form is automatically submitted. Everything seems to be working fine so far. However, there is a specific scenario where if a user selects a certain option in the form, it ...

Passing component properties using spaces in VueJS is a simple and effective

I am encountering an issue where I want to pass component props from my view, but I am facing a challenge due to the presence of a space in the value. This causes Vue to return the following error: vendor.js:695 [Vue warn]: Error compiling template: - inva ...

What is the best way to import information from a CSV or Excel file directly into my program?

I am currently using puppeteer for automating a form submission process. I am looking to extract data directly from a csv file and input it into the form. Can someone guide me on how to achieve this? The CSV file contains the following information: Fir ...

How can I incorporate percentage values into input text in Angular?

How can I include a percent sign in an input field using Angular, without relying on jQuery? I am looking for a solution that is identical to what I would achieve with jQuery. Here is the current status of my project: ...

Incorporating PruneCluster into an AngularJS Leaflet Directive for Enhanced Mapping

I am currently facing an issue with loading clustered markers for geojson data using PruneCluster. The clusters are not appearing on the map and there are no errors showing up in the console to assist with troubleshooting. Below is the snippet of my curr ...

Tips on sending data with a unique identifier to the backend through a route parameter

Can anyone help me figure out how to send a message to a specific backend route parameter while passing the current ID? I'm not sure how to inform the system about this ID. Here's the Vuex action: postMessage({commit}, payload, id) { axios.pos ...

Ways to adjust the text size in jqGrid?

The current theme is ui-lightness. How can I adjust the font size within the grid? Your suggestions are appreciated. Many thanks. ...

JavaScript: How to identify and select a specific item from a context menu

Currently diving into the world of JavaScript, so please keep that in mind when explaining. My main goal is to figure out a way to detect when a user triggers a right-click or uses the context menu from the keyboard. Specifically, I want to know if they s ...

Highlight particular terms (key phrases) within text contained in a <td> tag

I am currently working on a project and facing a challenge that I am unfamiliar with. My task is to highlight specific keywords within text located inside a <td> element. I cannot manually highlight the keywords as the texts are dynamic, originating ...

Submit a form utilizing jQuery's ajax function

I am currently facing an issue with my use of the $.ajax post method. My intention is to submit form data on the current page itself, but somehow the script is redirecting to the action page. If anyone could pinpoint what's causing this redirection ...

The node.js express framework is unable to fetch the URL and data from the node server

Attempting to create a basic application to retrieve data from a nodejs server. But encountering issues with accessing the file in both the browser and POSTMAN. Despite multiple attempts to verify the URLs, I have been unsuccessful. Below are the files i ...

The Restangular library seems to be struggling with handling query parameters

Currently, I am implementing Restangular in my Ionic application and trying to incorporate Infinite scrolling. To achieve this, I need to make a call using Restangular. As I refer to the Restangular documentation (here), I attempted the following approach ...