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

Encountering an issue while attempting to make changes and test a copied GitHub library - npm ERROR! version cannot be located

I'm new to the world of Github forking and pull requests. My goal is to fork a repository, make some changes, and test them out on a project before submitting a pull request. I've already forked the repository and made modifications, but I' ...

Next.js is unable to identify custom npm package

My unique custom package structure looks like this: package.json Posts.js Inside Posts.js, I have the following code: const Posts = () => { return <div>List of posts</div> } export default Posts; After publishing to the GitHub Package ...

Attempting to conceal the select input and footer components of the Calendar component within a React application

I am currently working on customizing a DatePicker component in Antd and my goal is to display only the calendar body. Initially, I attempted to use styled components to specifically target the header and footer of the calendar and apply display: none; st ...

An unexpected { token error was encountered by Jest while running a React application

I am facing a persistent issue that I just can't seem to resolve. Despite trying numerous solutions found online, nothing seems to fix it. Below are the configurations: package.json { "scripts": { "test": "jest --no-cache", ...

A beginner's guide to using Jasmine to test $http requests in AngularJS

I'm struggling with testing the data received from an $http request in my controller as I don't have much experience with Angular. Whenever I try to access $scope, it always comes back as undefined. Additionally, fetching the data from the test ...

I'm curious about the distinction between React's one-way data binding and Angular's two-way data binding. Can someone please clarify the key differences

My understanding of these concepts is a bit hazy. If I were to develop the same ToDo application using AngularJS and ReactJS, what exactly distinguishes React ToDo's use of one-way data binding from AngularJS's two-way data binding? From what I ...

A guide to navigating through a nested map with GSON

Looking to extract information from a JSON string in a specific format: { "request" : { "Format" : "json", "Method" : "method", "NetworkId" : "net", "NetworkToken" : "token", "Service" : "service", "Ta ...

Executing a javascript function from an ajax-loaded webpage

I have a form where I upload a file using an ajax call that includes an API request. Once the API call is successful, I need to update a table displaying the list of uploaded files. Initially, I attempted calling a JavaScript function within the ajax page, ...

combine various types of wrappers in React

We're embarking on a fresh project with React, and we will be utilizing: React Context API i18n (react.i18next) GraphQL (Apollo client) Redux CSS-in-JS (styled-components or aphrodite) The challenge lies in each of these implementations wrapping a ...

Is there a way to incorporate the req.setHeaders method with the res.redirect method in the same app.get function?

var express = require('express'); var app = express(); var PORT = process.env.PORT; app.get('/', function(req, res){ res.json('To search for images, enter your query parameters like this: https://api.cognitive.microsoft.com/bi ...

Minimize redundancy in the process of adding functions to a function queue

Currently, I am delving into JavaScript animations and utilizing multiple functions to add components to the animation queue. The structure of these functions is quite repetitive as shown below: function foo(arg1, arg2) { _eventQueue.push(function() { ...

What is the best way to ensure a cron job executing a Node.js script can access variables stored in an .env file?

Currently, I have a scheduled job using cron that runs a Node.js script. This script utilizes the dotenv package to access API keys stored in a .env file. Running the Node.js script from the command line retrieves the variables from the .env file successf ...

Mastering the art of Promises and handling errors

I've been tasked with developing a WebApp using Angular, but I'm facing a challenge as the project involves Typescript and asynchronous programming, which are new to me. The prototype already exists, and it includes a handshake process that consi ...

Angular2: Filtering an array based on the presence of items in another array

Looking to selectively filter out entries from an object array based on certain id values within another array. I've experimented with different methods but haven't found a solution that works yet. List of id´s: list = [1,3] Array to be filte ...

Implementing auto-population of input field in Vue JS based on dropdown selection

I'm in search of a solution for automatically filling input fields in Vue.js. My form consists of various input types such as text, select dropdowns, and quantities. I want the vCPU, vRAM, and Storage Capacity fields to be filled with predefined value ...

Tips for establishing communication between a React Native webView and a React web application

I am currently working on establishing communication between a webView in react-native and a web-app created with React-360 (and React). I am utilizing the react-native-webview library and following a guide for creating this communication. You can find the ...

showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. ...

Modify the background color of a div by selecting a hex code from a dropdown menu

Is there a way to utilize jQuery in order to alter the background of a <div> by choosing the HEX code from a separate dropdown menu? HTML <select id="target"> <option value="#c2c2c2">Grey</option> <option value="blue">Bl ...

Using TypeScript, what is the best way to call a public method within a wrapped Component?

Currently, I'm engaged in a React project that utilizes TypeScript. Within the project, there is an integration of the react-select component into another customized component. The custom wrapped component code is as follows: import * as React from " ...

"Using Java HttpServlet to send data as a Gson string, then retrieving it in JavaScript as

On the server side, I have this Java code snippet: public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json;charset=UTF-8"); resp.setHeader("Cache-Control", "no-cach ...