Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,708 questions

55,472 answers

573 users

How to sort an array of strings where each string represents a decimal number in Node.js

1 Answer

0 votes
// Comparator function to sort strings as decimal numbers
function compareAsDecimal(a, b) {
    // Convert strings to numbers for comparison
    const numA = parseFloat(a);
    const numB = parseFloat(b);
    
    return numA - numB; 
}

// Input array of strings
const numbers = ["11.3", "3.6", "89.1", "3.14", "456.0", "0", "0.001", "2.0"];

// Sort the array using the custom comparator
numbers.sort(compareAsDecimal);

console.log("Sorted array of decimal strings:");
console.log(numbers.join(" "));




/*
run:

Sorted array of decimal strings:
0 0.001 2.0 3.14 3.6 11.3 89.1 456.0

*/

 



answered Sep 1, 2025 by avibootz
...