Sorting an array of objects based on a combination of numbers and special characters

I'm currently facing an issue with sorting an array of objects based on the dimension property, which consists of number intervals and special characters. Here's a snippet of the data I have:

let data = [
  {
    "soldTickets": 206,
    "soldRevenue": 12825.309997558594,
    "playedOffTickets": 2915,
    "playedOffRevenue": 495923.22019958496,
    "dimension": "10 - 25",
    "ticketsChange": -2709,
    "revenueChange": -483097.91020202637
  },
  {
    "soldTickets": 172,
    "soldRevenue": 17174.29998779297,
    "playedOffTickets": 2485,
    "playedOffRevenue": 467017.27951049805,
    "dimension": "25 - 50",
    "ticketsChange": -2313,
    "revenueChange": -449842.9795227051
  },
  {
    "soldTickets": 122,
    "soldRevenue": 9892.249984741211,
    "playedOffTickets": 9121,
    "playedOffRevenue": 1129196.3203125,
    "dimension": "> 200",
    "ticketsChange": -8999,
    "revenueChange": -1119304.0703277588
  },
  {
    "soldTickets": 52,
    "soldRevenue": 3159.239990234375,
    "playedOffTickets": 544,
    "playedOffRevenue": 88893.0400390625,
    "dimension": "0 - 10",
    "ticketsChange": -492,
    "revenueChange": -85733.80004882812
  },
  {
    "soldTickets": 38,
    "soldRevenue": 3162.1099700927734,
    "playedOffTickets": 476,
    "playedOffRevenue": 92432.79023742676,
    "dimension": "100 - 200",
    "ticketsChange": -438,
    "revenueChange": -89270.68026733398
  },
  {
    "soldTickets": 37,
    "soldRevenue": 3233,
    "playedOffTickets": 590,
    "playedOffRevenue": 97645.46026611328,
    "dimension": "50 - 100",
    "ticketsChange": -553,
    "revenueChange": -94412.46026611328
  }
];

const toNumber = (str) => {
  if (Number(str)) {
    return Number(str);
  } else {
    return Number(str.substring(0, str.length - 1));
  }
};

   data = data.sort(
        (a, b) =>
          toNumber(String(a["dimension"]).split(' ')[0]) -
          toNumber(String(b["dimension"]).split(' ')[0])
      );
      
  console.log(data)

The problem lies in the sorting process as the result is not in the desired order. The > 200 entry should be last instead of first. The expected order is:

['0 - 10', '10 - 25', '25 - 50', '50 - 100', '100 - 200', '> 200']

I would appreciate any help or insights on what might be causing this issue. Thank you!

Answer №1

If we make the assumption that the first number is the criteria for sorting, a simple regex can be used to extract it and then sort based on it.

However, if the condition becomes more complex, like < 20, a re-evaluation of the sorting approach might be necessary.

For example:

let data=[{soldTickets:206,soldRevenue:12825.309997558594,playedOffTickets:2915,playedOffRevenue:495923.22019958496,dimension:"10 - 25",ticketsChange:-2709,revenueChange:-483097.91020202637},{soldTickets:172,soldRevenue:17174.29998779297,playedOffTickets:2485,playedOffRevenue:467017.27951049805,dimension:"25 - 50",ticketsChange:-2313,revenueChange:-449842.9795227051},{soldTickets:122,soldRevenue:9892.249984741211,playedOffTickets:9121,playedOffRevenue:1129196.3203125,dimension:"> 200",ticketsChange:-8999,revenueChange:-1119304.0703277588},{soldTickets:52,soldRevenue:3159.239990234375,playedOffTickets:544,playedOffRevenue:88893.0400390625,dimension:"0 - 10",ticketsChange:-492,revenueChange:-85733.80004882812},{soldTickets:38,soldRevenue:3162.1099700927734,playedOffTickets:476,playedOffRevenue:92432.79023742676,dimension:"100 - 200",ticketsChange:-438,revenueChange:-89270.68026733398},{soldTickets:37,soldRevenue:3233,playedOffTickets:590,playedOffRevenue:97645.46026611328,dimension:"50 - 100",ticketsChange:-553,revenueChange:-94412.46026611328}];

data = data.sort(
  (a, b) =>
    (a.dimension.match(/\d+/)[0] | 0) -
    (b.dimension.match(/\d+/)[0] | 0)
);
      
console.log(data)

ps. the val | 0, acts as a quick method to convert a string to a number, similar to Number(val) or parseInt(val, 10). Failure to convert to number may result in incorrect comparisons such as 200 being less than 30.

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

Extracting information from state and showcasing it in a dynamic layout using antd

When I try to use languages from the state in this line {({languages}, {add, remove}) => ...., I encounter a problem referencing the state. The error message .map is not a function is displayed. Upon clicking Add another languages, more input fields sho ...

The characteristics of angular js Service/Factory and how they influence functionality

I'm seeking clarification on the behavior of AngularJS, especially in terms of JavaScript. In my code, I have a controller that has an Angular factory injected into it. Here's a snippet from the controller: $scope.localObjCollection = myObjFac ...

Guide on setting up a Redirect URL with React Router

I am aiming to trigger a redirect URL event using ReactJS. Is there a way to achieve this? I have already attempted the following: successRedirect(){ this.transitionTo('/'); } as well as successRedirect(){ this.router.transitionTo ...

Activate Vuetify to toggle a data object in an array list when the mouse hovers over

I'm currently working on a project where I need to toggle a Vuetify badge element for each item in an array when the containing div is hovered over. While I've been able to achieve a similar effect using CSS in a v-for loop with an array list, I ...

determining the sorting behavior of columns in Datatables

While working on my table, I referred to a Datatbles tutorial that covers sorting the third column as a percentage value. // Setting up column search - adding a text input to each footer cell $('#p_table-id tfoot th').each(function ...

can you explain the concept of a backing instance in react?

Although the concept of a "backing instance" is frequently mentioned in React documentation, I found it difficult to grasp its meaning. According to the React docs: In order to interact with the browser, you need a reference to a DOM node. By attaching ...

The duplication of printed keys and values from a JavaScript object is causing issues

I am working with a JSON object structured like this: var data = { "2020-01-20": ["08:00 - 09:00", "09:00 - 10:00"], "2020-01-21": ["08:00 - 09:00"] }; My objective is to display each value along with its corresponding key in a list format, as follow ...

Converting PHP date format to JavaScript date format

I'm struggling to solve this problem $datetime = new Date().toLocaleString(); // returns current date in format 10/21/2021, 14:29:43 How can I generate the desired date format using JavaScript? The output should look like this: 2021-10-21 16:30:01 ...

Update the HTML weather icon with data from JSON

I have a collection of weather icons stored on my computer. How can I customize the default weather icons with my own set of icons? In the JSON file, there is a variable like this: "icon":"partlycloudy" <html> <head> <script src="http://c ...

JavaScript facing issue with $.get command executing in incorrect order

I have encountered an issue with my JavaScript code where it is not running in sequence. The script includes an unload function that uses the $.get jQuery command to fetch a file, which is then supposed to be printed to an external device. To debug this ...

What is the correct way to properly import a non-relative path in TypeScript?

Struggling with importing into my TypeScript class. // Issue arises here... import * as Foundation from 'foundation/foundation'; // Everything runs smoothly until the above import is added... export class HelloWorldScene { constructor() { ...

What is the most effective method for implementing popups and dialogs using JQuery?

I had previously created popups/dialogs, but have now encountered a regression error when trying to use them. I am looking to recode them using JQuery for the DIVs/popups/dialogs. Transitioning to JQuery would offer the advantage of enabling repositioning ...

Avoid allowing users to accidentally double click on JavaScript buttons

I am working with two buttons in a Javascript carousel and need to prevent users from double-clicking on the buttons. Below is the code I am using: var onRightArrow = function(e) { if (unitCtr<=unitTotal) { unitCtr++; TweenLite.to(p ...

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

Manipulating rows [using an input field] within a table

As someone new to JavaScript, I tried my hand at coding the following piece after tweaking a tutorial I stumbled upon. The aim was to have rows with input fields added and removed within a table, but unfortunately, nothing happens when running the code. ...

Tips on adding style to your jQuery autocomplete dropdown

I am currently utilizing jQuery autocomplete functionality. I have configured it to communicate with a service and retrieve records: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1 ...

What is a more effective method for linking values with variables in an object?

Can you suggest a more efficient way to write this in JavaScript? let foo; if(bar) { foo = bar.value; } I am attempting to prevent a react error from occurring when `bar` is null if I were to use const foo = bar.value. ...

Having trouble with CSS and javascript files not resolving after moving app to a new Windows 7 development machine

I have recently migrated my ASP.Net 3.5 web site from my old XP sp3 machine to a new Win 7 64-bit dev machine. The web application utilizes Master Pages, App_Themes with style sheets and images, as well as an image folder located off the main root. Additio ...

"Interactive demonstration" image toggle through file upload

I have a project to create a "demo" website for a client who wants to showcase the template to their clients. A key feature they are interested in is allowing users to upload their logo (in jpg or png format) and see it replace the default logo image insta ...

`Increase Your Javascript Heap Memory Allocation in Next.js`

We are facing a challenge with the development environment for our Next.js application. Issue The Javascript heap memory is consistently depleting. Here are the specific error logs: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out ...