What is the best way to organize an array that contains empty strings, NaN, numeric values, and infinity?

Looking for help with sorting an array containing various types like empty strings, numbers, "infinity", "-infinity", and "NaN". The values are all in string form which is causing issues with the default sort function when it comes to empty strings and special cases like 'inf' and 'nan'. Is there a way to customize the sorting function to work properly in both ascending and descending order?

Answer №1

To adjust the order of a given array, you can utilize an object to define the desired sort order and then rearrange the elements accordingly.

var array = ["", 2, 3, 0, "inf", "-inf", "Nan", -1, -100000];

array.sort(function (a, b) {
    var order = { "": -4, "-inf": -3, "Nan": -2, "inf": -1 };
    return (order[a] || 0) - (order[b] || 0) || a - b;
});

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

Answer №2

Update: based on the feedback provided, the ordering sequence is as follows:

"" < "-inf" < "Nan" < "inf" <  ... < -1 < 0 < 1 < ...
. To customize this, you can adjust the elements in the order array.

Keep in mind that if the array includes items not listed in the order array, the code may not function correctly. To address this, consider implementing safeguards or including additional special elements (such as 0) in the order array.

It's important to note that in JavaScript, NaN and Infinity (not as string literals) are also considered numbers. This code ensures they are sorted alongside numerical values.

var basicCompare = function (a, b) {
    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
}

var compare = function (a, b) {
    // 0 denotes numbers.
    var order = ["", "-inf", "Nan", "inf", 0],
        orderOfNumber = order.indexOf(0),   
        orderOfA = typeof(a) === "number" ? orderOfNumber : order.indexOf(a),
        orderOfB = typeof(b) === "number" ? orderOfNumber : order.indexOf(b);

    if (orderOfA === orderOfNumber && orderOfB === orderOfNumber) {
        // Both are numbers, utilize standard comparison.
        return basicCompare(a, b);
    }

    // If not both numbers, apply the predefined order.
    return basicCompare(orderOfA, orderOfB)
}

array.sort(compare);

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

Creating a seamless thread using AngularJS

I am working on a Spring MVC application that utilizes HTML and Angular on the client side. I have a method in my Angular controller that needs to run every 5 seconds. How can I achieve this using Angular? Thank you for your assistance. $scope.inspectio ...

JQuery functionality not functioning properly following an AJAX page reload

Currently, I am utilizing a jQuery code to select all checkboxes in the following manner: var JQ7=jQuery.noConflict(); JQ7(document).ready(function(){ JQ7("#chkAll").click(function(){ JQ7(".chk").prop("checked",JQ7("#chkAll").prop("checked")) }) }); ...

Sending an image from a NodeJS socket server to another server: The ultimate guide

Hello there, I'm currently working on a new project and I could really use your input on a challenge I'm dealing with. Here's the situation: I have a web server running a socket.io module. The server is listening on port 3012 and streaming ...

What makes fastify-plugin better than simply calling a regular function?

I recently came across a detailed explanation of how fastify-plugin operates and its functionality. Despite understanding the concept, I am left with a lingering question; what sets it apart from a standard function call without using the .register() metho ...

What is the standard "placeholder" for a Select-box in Angular?

Currently in the process of developing a front-end web application with Angular 6, I have encountered a challenge. Specifically, I am working on creating a component that includes various select-boxes, resembling this setup: https://i.sstatic.net/6DmL9.pn ...

generate an array using JavaScript and Html.action

I'm struggling with creating an array of strings in JavaScript using a function within my MVC controller. The current approach is not yielding the desired results, and I'm unsure of the necessary steps to rectify this issue. Below, you'll fi ...

Run custom JavaScript code dynamically within a webpage

What is the most effective way to use Java to automatically open a web page, run some JavaScript to complete and submit a form, and analyze the outcome? ...

Using Jquery to insert new rows into a table

Here is the code for my button and table: <button type="button" class="btn btn-md" id="addRowBtn">Test Button To Add Row</button> <table id="tableForRows"> <tr> <td> </td> </tr> </tabl ...

Challenges with converting C++ text files into arrays with multiple dimensions

For a school project, I am trying to convert an inventory file in .txt format into an array using C++ and later revert it back to a .txt file at a different stage of the program. The text file contains 10 rows initially, representing grocery store items w ...

Incorporating .json files into an HTML template with the help of an HTML form designed for selecting a particular

I am faced with a collection of various .json files that I wish to specify by name on an HTML page (local) form, enabling me to load this data onto a table. This is how my HTML form appears: <form> File: <input type="text" Id="file_name"&g ...

Make sure to include `jquery` in the types section of your tsconfig file

I've encountered an issue while trying to use jQuery in my Angular-TypeScript project. After installing jquery using "npm install @type/jquery", I am receiving the following error when trying to serve: Error TS2592: Cannot find name '$'. Is ...

watchify with gulp requires two saves to update modifications

For a while now, I've been experimenting with watchify and encountering a saving issue. It appears that every time I make a change, I have to save twice for the modifications to reflect in the output. If I add new code to any JavaScript file, the ch ...

Is there a way to send a form without having to display it beforehand?

I am looking to create a hidden form that can be submitted using form.submit. Using Ext.Ajax.request is not an option for me because I need to upload files as well. This is what I currently have: function uploadRequest(){ var hiddenTextField = new Ext. ...

Hearing the reflow event within the browser

In an attempt to track browser reflow events, I am exploring ways to identify the most resource-intensive parts of my code. Reflow happens when something needs to be redrawn on the screen, such as when a new element is added to the DOM. Is it possible to ...

What sets apart the use of `function(){}.bind(this)` and `angular.bind(this, function() {})`

Can you highlight the difference between these two code snippets? function Ctrl($scope) { $scope.$watch(function() { return this.variable; }.bind(this), /*...*/); } and function Ctrl($scope) { $scope.$watch(angular.bind(this, functio ...

Sending information to the struct from iphdr

Although I am not a C programming expert, I have ventured into capturing and analyzing packet data using C. However, I encountered an issue where I couldn't transfer the data to the variables inside the structs. Let me show you my structs: struct ipO ...

Creating fixed-size arrays within a Mongoose schema is a commonly sought after feature that allows

For a specific scenario where I have example input: [[1,2],[3,2],[1,3],...,[4,5]] I am wondering about the correct way to define a model schema in mongoose. Here is my initial Schema: const SubproductSchema = new Schema({ ... positions: [{ type: ...

Loop through a JSON document in PHP

Looking to filter through a JSON file containing a global list of universities to find specific ones based on a selected field. The main challenge is dealing with individual ID numbers assigned to each university in the array, making it tricky to iterate o ...

Issues with Angularjs in production when used with Rails

I am currently facing an issue while attempting to deploy a Rails application with Angularjs on Bluemix. AngularJS is being used for the front end MVC. Despite the application running smoothly on my local machine, when deployed on Bluemix, Angularjs fails ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...