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

Guide on saving multiple PDF files in the public directory using Laravel 8 controllers

I am currently facing a challenge in storing my PDF files in the public folders. Does anyone have any suggestions on how to achieve this? I attempted to iterate through the data to access the file, but unfortunately, it is not working as expected on my en ...

Development is hindered due to Cors policy restricting access to the localhost webapp

Currently, I am working on developing a web application and an API simultaneously, but I'm facing some issues with CORS blocking. This concept is relatively new to me, and I'm eager to improve my understanding. Firstly, I have set up an Express ...

jQuery-powered Ajax file upload progress bar

Although I don't rely on jQuery for everything, I do find it useful for tasks such as AJAX. But currently, I'm facing some challenges with it. Here is a piece of code that should update my upload progress bar while the upload process is ongoing. ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

The data sent within an event does not trigger reactivity

Not producing errors, just failing to function. The addition of this also has no impact. input( type="number" v-model="myData" @wheel="wheelIt($event, myData, myMethod)" ) ... methods: { wheelIt ( event, data, func ) { if ( event.deltaY ...

What could be causing the JavaScript array to not successfully transfer to PHP?

Despite searching for solutions, I am unable to get the desired outcome. When I check my JavaScript array in the console, it appears like this: [] 0:Object stock:27 createdtime:"2016-04-08T04:00:00+0000" id:"693852404037393999" units:438 ...

steps for executing a Google script

In my program, the structure is as follows: // JavaScript function using Google Script 1. function F1() { ...... return (v1); } // HTML code for Google 1. <script> 2. function F2() { 3. alert ( 1 ); 4. function F2(); 5. alert ( 2 ); 6 ...

A guide on organizing a 2D array with the bubble sort method

I am struggling with sorting a 2D array in descending order by row using bubble sort based on the last column. The data needs to be organized in descending order, but only according to the values in the last column. 6814.00 85.00 86.00 92 ...

Using val() on a checkbox will give you an element, not a string literal

How can I retrieve only the literal values of all checked checkboxes without any additional data? My current approach is: $('input:checked').map(function() { return $(this).val(); }) The result that I am getting looks like this: e.fn.init[1]0 ...

How to Implement Drupal.behaviors for Specific Pages?

Currently, I have a module that showcases an alert to users within a block. For those interested, you can find my code on GitHub here: https://github.com/kevinquillen/User-Alerts If you would like more information about the module and its functionality, ...

Is there a way to streamline this generator without using recursion?

I need to develop a unique value generator that produces values within a specified range. The criteria are: all generated values must be distinct the order of values remains consistent upon each run of the generator each value should be significantly diff ...

In Angular 2, how does the "this" keyword from the subscribe method reference the class?

I am using a subscription for Observable, and when it finishes I need it to call a function from this class. The issue is that the "this" keyword refers to the subscription and not to the class scope. Here is the code snippet: export class GoogleMapCompo ...

Custom Mui table sizes - personalized theme

By implementing custom sizes for the Table component in Material UI, I have extended the Table size prop with the following declaration: declare module '@mui/material' { interface TablePropsSizeOverrides { relaxed: true large: true } ...

Sending the `<path>` wrapped in quotes to `<SvgIcon>` is resulting in the SVG not rendering

When I try to use the Material-UI's SvgIcon component, the <path> element is surrounded by quotes, which is preventing the SVG from rendering properly. https://i.stack.imgur.com/InDRt.png I'm currently working in Storybook within an MDX f ...

How can we efficiently load and display all images from a directory using Node.js and JavaScript?

My strategy involves reading all image file names from a specific directory and passing them as an array to the front-end JavaScript. The front-end script then iterates through the array to dynamically create image elements. Step 1: node const path = requ ...

Guidance on invoking the navigate function from a component displayed at the highest level of rendering

Within the react-navigation documentation, it is explained that you can initiate navigation from the top-level component using the following method: import { NavigationActions } from 'react-navigation'; const AppNavigator = StackNavigator(SomeA ...

Guide to building a hierarchical data object with JavaScript

Prior This object consists of multiple rows: { "functions": [ { "package_id": "2", "module_id": "2", "data_id": "2" }, { "package_id": ...

Calculating a 30-minute interval between two given times using JavaScript/jQuery

My goal is to generate a list of times between a specified start and stop time, with half-hour intervals. While I have achieved this using PHP, I now wish to accomplish the same task using JavaScript or jQuery. Here is a snippet of my PHP code which may ...

Error message: Unable to locate local module in node.js subdirectory

Exploring the folder structure within my application https://i.stack.imgur.com/Pkxpg.png Referring to app_modules/bar and app_modules/foo as local modules Root Folder package.json "dependencies": { "body-parser": "~1.18.2", "cookie-parser": "~ ...