How to Sort Numbers Correctly with Array.Sort()

How to sort numbers correctly with Array.sort()?

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

array.sort([compareFunction])

Parameters

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return −1.
19. If Result(16) > Result(17), return 1.
20. Return +0.

How to sort an array of integers correctly

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});

console.log(numArray);

Why does numberArray.sort() not sort numbers correctly in JavaScript?

sort() function considers everything in the Array as String if it is called without custom ordering function.

The only exception is undefined, which is from Javascript 1.2 always the "largest" item in the sorted array.

[void(0),342,4.5,"ahahaha",null,"zzz", "nen", "nup", 0/0, "KDSFL", "-sdfh",-3324, "-%",Array.prototype.sort,window,Array.zzz,"[oooooo]", "undefined",0].sort()

Reference:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

Sort an array which contains number and strings

It seems you have done most of the work in your second attempt.
All I have done here is used Array.concat to join the sorted results of number and char together.

var arr = [9, 5, '2', 'ab', '3', -1] // to be sortedvar number = [];var char = [];arr.forEach(a => {  if (typeof a == 'number') number.push(a);  else char.push(a);})

var sorted = number.sort().concat(char.sort());console.log(sorted)

How to sort array of numbers that includes negative values using localecompare?

Because your array items can be coerced to numbers directly, why not do that instead?

var array = ["-394","-275","-156","-37","82","201","320","439","558","677","796"];array.sort(function(a,b) { return a - b } );console.log(array);

How to sort a javascript array alphabetically with numbers at the end (after letters), and correctly sorting numerically?

You could check if the string starts with a digit and sort the rest by groups.

const array = ['10 FOOT', '45 RPM', '9 VOLT', '910D0', 'AGUA', 'BEAST', 'KEN 5', 'NEMCO'];

array.sort((a, b) => isFinite(a[0]) - isFinite(b[0])
|| a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
);

console.log(array);

JavaScript sorting numbers not working as expected

You need to use a sort function. By default sort uses alphabetic sorting instead of numeric.

array1.sort(function (a,b) {
return a - b; // Ascending
});

array1.sort(function (a,b) {
return b - a; // Descending
});

Trying to sort array by numbers first and then letters last

You can try to compare them like this

product_data.sort(function(a, b) {
return a.itemCommodity > b.itemCommodity;
});

And if you want the order of the letters to be sorted then you can try this

 product_data.sort(function(a, b) {
return a.itemCommodity.toLowerCase() > b.itemCommodity.toLowerCase();
});

Trying to follow a numerical array sort steps in Javascript

The specific sorting algorithm used is not specified by the specification; a JavaScript engine is free to use any sorting algorithm it likes, whether that's a bubble sort, a quicksort, or something else. But yes, sorting algorithms in general need to do more than just a single pass through the data and one comparison per element. Much more.

Javascript Array Sort function not sorting properly

It's because you're sorting the numbers with the default sorting algorithm, which converts them to a string and sorts lexicographically.

Instead pass a function defining a sort order via its return value.

var arr = [23,43,54,2,3,12]; 
console.log(arr.sort((a, b) => a - b));


Related Topics



Leave a reply



Submit