Arranging an array of integers followed by sorting by the decimal part of each value in a particular sequence using JavaScript

Below is an example of sorting an array:

let arr = ['100.12', '100.8', '100.11', '100.9'];

When sorted traditionally, the output is:

'100.11', '100.12', '100.8', '100.9'

However, I want it to be sorted like page numbers:

'100.8', '100.9', '100.11', '100.12',


EDIT: While there are some solutions available, they lack accuracy in certain cases such as this one:

arr1 = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9']

The result would look like:

["77.8", "77.9", "77.11", "77.12", "77", "88", "100.8", "100.11", "100.12", "100", "100.9", "119", "120"]

What is expected should look like:

[ "77", "77.8", "77.9", "77.11", "77.12", "88", "100", "100.8", "100.11", "100.12", "100.9", "119", "120"]

Answer №1

To arrange your array in numerical order, you can utilize the string#localeCompare method along with the numeric property.

let arr = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9'];
arr.sort((a, b) => a.localeCompare(b, undefined, {numeric: true}))
console.log(arr)

Answer №2

Sorting numbers based on integer and decimal parts.

const arr =  ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9'];
const sorted = arr.sort((a, b) => {
      if (parseInt(a) !== parseInt(b)) {
        return parseInt(a) - parseInt(b);
      }
      return (parseInt(a.split('.')[1], 10) || 0) - (parseInt(b.split('.')[1], 10) || 0);
    });
    
console.log(sorted);

Answer №3

If you want to effectively compare and arrange numbers based on their digits and decimal segments, one approach is to implement a custom sorting function. This function will first evaluate the integer parts of the numbers. If those are not equal, it will then move on to comparing the decimal sections:

let values = ['100.12', '100.8', '100.11', '100.9'];

function myCustomSort(num1, num2) {
    const [int1, dec1] = num1.split('.').map(Number);
    const [int2, dec2] = num2.split('.').map(Number);

    // Compare the integer parts initially
    if (int1 !== int2) {
        return int1 - int2;
    }

    // If the integer parts match, compare the decimal parts
    return dec1 - dec2;
}

values.sort(myCustomSort);

console.log(values);

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

Implementing an interface in TypeScript and assigning it a value using generics?

I'm struggling to make sense of a type declaration I came across in the react-router library: export interface RouteComponentProps< Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.Lo ...

Get Onsen UI 2 up and running without the need for Angular

Is it possible to install Onsen UI 2 without Angular? I have tried following various guides from , but when attempting the JavaScript method (> npm install onsenui) I consistently encounter a ReferenceError: angular is not defined. How can I properly ins ...

What steps are involved in creating a default toolbar for a material picker in a React application?

Looking for assistance with customizing the toolbar for material picker (v3) by adding a title inside the dialog. I successfully implemented this in the KeyboardDatePicker following a helpful thread (https://github.com/mui-org/material-ui-pickers/issues/11 ...

Updating image source dynamically with Flask

I am currently developing a face detection application using Flask. I aim to have the detected faces displayed in real-time on the HTML page. For the JavaScript aspect, I am utilizing getUserMedia to live stream camera images from the client to the server ...

Retrieve an image from the server and display a preview of it on the client side

I'm currently in the process of fetching an image from a server and previewing it on the client side. I have successfully retrieved the image, but I am unsure of how to asynchronously display it on a web page. axios.get(link,{responseType:'strea ...

"Is there a way to adjust the range slider to display currency instead of

I stumbled upon this amazing slider on codepen. Can someone guide me on how to adjust it to display a range from €500 to €6000 while keeping the vibrant red background? I've attempted various solutions like: <input id = "range" type = "range ...

Rebuilding associative arrays using PHP

I'm attempting to reconstruct this array using a foreach loop : Array ( [0] => Array ( [ID] => 0 [NAME] => 400 [QUANTITY] => 12 ) [1] => Array ( [ID] => ...

Personalize buttons using SweetAlerts 2 customization options

In order to adhere to the custom design provided to me, I am currently using SweetAlerts 2 for all dialog boxes that require confirmation or cancellation. Specifically, I require the cancel button to have a white background with teal text and a teal border ...

Find the difference between the sum of diagonals in a 2D matrix using JavaScript

I'm currently practicing on hackerrank and came across a challenge involving a two-dimensional matrix. Unfortunately, I encountered an error in my code implementation. 11 2 4 4 5 6 10 8 -12 The task at hand is to calculate the sum along the primary ...

Retrieving Mouse Coordinates using Ajax in PHP

I'm wondering if it's feasible to send an Ajax request with mouse coordinates using PHP. For instance, I am fetching a page with cUrl and would like to trigger a mouse movement event on that page. At this point, I haven't written any code ...

Tips for positioning a grid at the center of a MaterialUI layout

I am struggling to position 3 paper elements in the center of both the vertical and horizontal axes on the screen. Despite applying various CSS rules and properties, the height of the HTML element consistently shows as 76 pixels when inspected in the con ...

Switch or toggle between colors using CSS and JavaScript

Greetings for taking the time to review this query! I'm currently in the process of designing a login form specifically catered towards students and teachers One key feature I'm incorporating is a switch or toggle button that alternates between ...

tips on retrieving attributes from a javascript array

I am trying to access the title attribute from an array with only one data record. When I use console.log(data), it displays the result as shown in the picture below. However, if I use console.log(data[0].attributes.title), it returns 'undefined' ...

Issue with index creation using the @index decorator in Typegoose with NestJS and MongoDB

Encountering an issue with typegoose. Trying to create a 2dsphere index on the property geoLocation of model SP. Utilized the typegoose decorator @index but it's not functioning and not throwing any errors. Uncertain about how typegoose handles this s ...

The window.onload function is ineffective when implemented on a mail client

Within my original webpage, there is a script that I have created: <script> var marcoemail="aaaaaa"; function pippo(){ document.getElementById("marcoemailid").innerHTML=marcoemail; } window.onload = pippo; </script> The issue a ...

Discovering whether an ID exists within a variable containing HTML code

I am currently attempting to determine if the ID is included in a variable containing HTML content. The ID name is being added to a DIV element through dynamic variables. strHTML = "<div id='"+var1+var2+"'>" Now, I want to verify if a sp ...

Retrieve the name of the path for the specified * stack within Express.js

When working with Express.js, I am utilizing '*' to catch the error 404. Is there a way for me to find out the path name of the error URL? app.get('*', (req, res) => { console.log("route: " + JSON.stringify(req.route) ...

JavaScript: Incorporating an operator into a specific object (instead of the entire class)

Are you familiar with how to include an operator in an object (rather than the entire class)? When it comes to a method, I know you can achieve that by: my_object.new_function = function(){return 1}; Then invoking my_object.new_function() will output ...

Extracting a particular element from a sophisticated auto-complete DOM structure by drilling down into the $scope

After spending a significant amount of time trying to solve this problem, I find myself at a dead end. The simplicity of using jQuery makes me reconsider Angular, but perhaps my approach is flawed. In this scenario, the DOM structure looks like this: < ...

What is the best way to add methods to underscore without making them available globally?

Have you added multiple methods to underscore within your package? _.mixin({ foo: function() {}, bar: function() {} //etc }); If you're concerned about potential conflicts with the main application or other packages, what's the best way ...