1368

Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought.

var numArray = [140000, 104, 99];
numArray = numArray.sort();
console.log(numArray)

I'd expect this to show 99, 104, 140000. Instead it shows 104, 140000, 99. So it seems the sort is handling the values as strings.

Is there a way to get the sort function to actually sort on integer value?

johannchopin
  • 13,720
  • 10
  • 55
  • 101
peirix
  • 36,512
  • 23
  • 96
  • 126
  • 6
    BTW, if you're sorting *lots and lots* of integers it will be advantages to use an integer sort algorithm like [counting sort](https://github.com/arnorhs/javascript-counting-sort/blob/master/index.js). The time counting sort will take to run scales linearly with the size of your array: O(n). Whereas all solutions here use comparison sort which is less efficient: O(n * log n). – Web_Designer Jun 08 '17 at 22:08
  • 4
    @Web_Designer Counting sort is linear regarding the number range, not the array. For example, sorting [1,1000000] will take more than 2 steps, since the algorithm will have to scan each array index between 1 to 1000000 to see which cell's value is greater than 0. – yters Feb 13 '18 at 15:05
  • 2
    @yters Using a hashmap, you can only pay attention to the integers that show up in the array being sorted. This makes the sort linear wrt the array size. – Kevin Dec 19 '18 at 14:02
  • 1
    the quickest way is to use the isomorphic [sort-array](https://github.com/75lb/sort-array) module which works natively in both browser and node, supporting any type of input, computed fields and custom sort orders. – Lloyd Oct 21 '19 at 20:27
  • @Quuxplusone This question is about sorting numbers, and `NaN` is not a number. Dealing with NaN is only relevant in cases where you expect to have NaN, which is a small subset of cases in which we have an array of numbers. – ICW Dec 18 '19 at 20:49
  • @Web_Designer: Also using counting sort on `[140000, 104, 99]` will allocate and operate on arrays with 140000 elements. Beware!! – Peter V. Mørch Jan 01 '20 at 19:38
  • 8
    It's pretty insane that JS still has this bug... – user894319twitter Feb 10 '21 at 10:18
  • @user894319twitter it's not a bug, that's how `Array.sort()` is specified to work. But I agree that it's insane, one of the many quirks that make JavaScript not the greatest language in the world... – Jesper Mar 27 '21 at 20:28
  • 5
    @user894319twitter it's unreal, I honestly can't call it anything then a bug. If that's in the spec then they specified a bug in the specs. It's a bug. – gjvdkamp Jun 17 '22 at 23:26
  • 1
    I would really like to know the thought process that led to the conclusion "this is a good implementation of sort()". – Welcor Feb 25 '23 at 22:22

32 Answers32

1955

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);

Documentation:

Mozilla Array.prototype.sort() recommends this compare function for arrays that don't contain Infinity or NaN. (Because Infinity - Infinity is NaN, not 0).

Also examples of sorting objects by key.

Sergio Abreu
  • 2,686
  • 25
  • 20
aks
  • 24,359
  • 3
  • 32
  • 35
  • 228
    Nice. But is there really no out-of-the-box way to get a numerical sort from javascript? – peirix Jun 30 '09 at 10:49
  • 47
    ahah this is out of the box! But if you're really impractical you can bind functions to the array class class at the very beginning of your javascript: // Array.prototype.sortNormal = function(){return this.sort(function(a,b){return a - b})} // Now calling .sortNormal() on any array will sort it numerically – Jack Franzen Oct 21 '13 at 01:22
  • 2
    I have a requirement that it should not change the position of an array element when a = b. But above code changes array elements positions even though their values are same. Is there any workaround? Thanks – Krishna Shetty Nov 27 '14 at 16:39
  • 17
    Why a-b and not a>b. I suggest the last one in order to avoid operation machine errors – Luca Davanzo Apr 02 '15 at 13:46
  • 56
    @Velthune The compare function should return -1, 0 or +1. a>b will only return true or false. – Iván Pérez Sep 28 '15 at 10:21
  • 1
    The compare function can return all the numeric value. The document: [Array.prototype.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – Константин Ван Dec 28 '15 at 09:37
  • 67
    This code can be shortened using an [Arrow Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). `numberArray.sort((a, b) => (a - b));` Yay! I think this is close to the out-of-the-box way. **Note: check if your JS engine supports Arrow Functions.** – Константин Ван Dec 28 '15 at 09:41
  • 9
    Javascript did not bother to implement number sort? What is the reasoning behind this? – Peter Raeves Jul 06 '16 at 11:00
  • @K._ - I disagree that this is close to out of box way - you are using a side effect of the arrow syntax to cut out the words "function" and "return", but are not actually using the arrow function's true purpose of passing "this". I would strongly discourage others from using an arrow function here, as it implies there is some "this" context passing happening, but there isn't. Confusing for other developers to read your code, just to save a few chars. – bambery Dec 02 '16 at 04:49
  • 9
    @K._ -- You don't actually need the parentheses: `.sort((a, b) => a - b)` -- so it's even shorter. – John Weisz Apr 28 '17 at 13:55
  • 1
    I don't understand why this works? Why even `a - b` and not `a < b` ? – Black Feb 12 '18 at 20:52
  • 5
    @Black you should read the Array.prototype.sort() documentation page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort You pass in a compare function to `sort()` that should return a value that's greater than zero, less than zero, or zero. – Eugene Kim May 25 '18 at 20:01
  • 2
    @Black It's simply what `sort()`'s compare function expects. Have you read the linked documentation? When `sort()` runs, it accounts for three cases and a boolean expression doesn't suffice. When determining the order of two objects `a` and `b`, `sort()` determines that: (1) `a` comes before `b`, (2) `b` comes before `a`, or (3) `a` and `b` should be left in the order they came in with respect to each other but sorted with respect to the other elements in the array. Having the comparator function return a number that's `> 0`, `0` or `< 0` maps to the described scenarios nicely. – Eugene Kim May 27 '18 at 06:41
  • You can make a true numeric sort by using parseInt() around the inputs. This way it will also work with numeric filenames for example: `numArray.sort((a, b) => parseInt(a) - parseInt(b));` – Thomas Lobker Jun 08 '18 at 21:55
  • 2
    @vikramvi `sort()` expects a negative number if `b` should go after `a` in the order, or a positive number if `a` should go after `b`. `a-b` is negative when `b` is bigger than `a` and should go after `a`, and positive when `a` is bigger than `b` and should go after. Using `b-a` reverses it - now it's negative when `a` is bigger than `b` and should go after `a`. Example: `[1,9]`: `1-9 = -8`, so `9` should go after `1` in ascending order - conversely, `9-1` is `8`, so `1` should go after `9` in descending order. – Marks Polakovs Jul 22 '19 at 11:45
  • @JackFranzen This is absolutely not out of the box. It requires a very specific configuration of a function that is out of the box. The configuration itself is extremely unintuitive. If Javascript were better designed, `.sort()` would simply sort an array of integers correctly with none of this function passing nonsense. – ICW Dec 18 '19 at 20:51
  • 1
    @YungGun: And how would your hypothetical better design sort `[42, '99', false, {x: 3}, new Rectangle(10, 5), /\s/g, 'true', new Date(1776, 6, 4)]`? – Scott Sauyet Feb 27 '20 at 15:51
  • @YungGun: I would hope that such an array wouldn't exist. Yet the language supports it; it's one of the downsides of dealing with a dynamically typed language. But you want a numeric sort. Someone else wants a case-insensitive descending sort. A third person wants to sort by date, ignoring time. Still someone else wants to sort by the 'age' property of their objects. Some idiot wants to sort that list above by the third character of elements' `toString` representation. Etc. It becomes really difficult to design any API that handles all this. But it's simpler to let the user decide. – Scott Sauyet Feb 27 '20 at 17:25
  • Arrow functions are nice and shorter, but even without them the code can be written more concisely (in one line): `numArray.sort(function(a, b) { return a - b; })` – Dave F Apr 03 '20 at 03:54
  • @IsaacCWay The reason modern Javascript requires you to pass functions is because most serious Javascript programmers deal with arrays of objects rather than just arrays of numbers. Take this for example `var x = [{ title: "world", number: 10 }, { title: "hello", number: 5 }, { title: "world", number: 20 }, { title: "goodbye", number: 15 }];` I want this array to be sorted by the number value, but I will then output the title value in that order. `console.log(x.sort((a, b) => a.number - b.number).map(x => x.title).join(" "));`. In this case I chain three array functions to output the titles. – Zei Jun 22 '21 at 22:12
  • @SergioAbreu (or anyone with enough privilege) please undo the 2022-Aug-27 edit. (I tried but the queue is full.) The 13-year history of this answer and its comments are about the simple function a - b, not the function that compares a with Infinity and NaN. That new function belongs in a new answer (or nowhere, because it still returns NaN when a and b are both -Infinity or when b is NaN). Thanks! – Adam M. Costello Sep 21 '22 at 04:43
  • actually an insane person's idea of how .sort() should work for an array of numbers – Roman Scher Feb 03 '23 at 22:54
  • @ScottSauyet you should literally never have an array containing different types like that – ICW Aug 16 '23 at 14:57
  • @ICW: Certainly, you should never create one like that. Moreover, sorting it is a stupid idea. But as such things are possible in the language, generic language tools like `Array.prototype.sort` must be written to account for them.... Also, I've had some pretty terrible upstream systems I've had to deal with; haven't most of us? – Scott Sauyet Aug 16 '23 at 17:06
221

Just building on all of the above answers, they can also be done in one line like this:

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

//outputs: 99, 104, 140000
Machavity
  • 30,841
  • 27
  • 92
  • 100
MarzSocks
  • 4,229
  • 3
  • 22
  • 35
  • 1
    I think you mean in one expression. – maxjvh Dec 04 '15 at 12:26
  • 16
    @bodyflex Fixed: `var arr = [140000, 104, 99].sort(function(a,b) { return a-b; });`. Or more compact, in ES6 `let arr = [140000, 104, 99].sort((a,b) => a-b);` – 00500005 May 17 '16 at 16:18
153

I am surprised why everyone recommends to pass a comparator function to sort(), that makes sorting slow.

To sort numbers, just create any TypedArray:

var numArray = new Float64Array([140000, 104, 99]);
numArray = numArray.sort();
console.log(numArray)
dy_
  • 6,462
  • 5
  • 24
  • 30
  • 7
    Using a TypedArray speeds up sort by about 5X. If you want to go even faster hpc-algorithms npm package implements Radix Sort and Counting Sort that several answers here suggest. – DragonSpit Aug 10 '19 at 02:26
  • I tried this with negative numbers and had a strange result: `> new Uint32Array([ -4, -7, 1, 4 ]).sort()` returned `Uint32Array(4) [ 1, 4, 4294967289, 4294967292 ]`. – Nikolay D Sep 05 '20 at 12:24
  • 15
    @Nikolay D those are unsigned. You can use Int32Array. – rion18 Sep 05 '20 at 19:07
  • 1
    sure sorting a typed array is faster. But if you have a regular array, converting it to a typed array to sort it is not a good solution (speed and memory) – Gio Oct 30 '20 at 10:56
  • 4
    @Gio not sure that is true. Memory requirement is only O(2n) which is only a couple megabytes for an array of million items. As for speed - converting array to typedarray, sorting and converting back is still faster than sorting an array with a function. – dy_ Oct 31 '20 at 14:20
  • 2
    Using custom sorting function sort((a, b) => a - b) is very fast. The only benefit from using a Typed Array comes when dealing with huge arrays and it doesn't support dynamic size or push and instantiating one also takes more time than [] so it all depends on usage. I'd say if you're dealing with less than 20k element arrays don't bother with typed arrays. – Pawel Sep 12 '21 at 19:32
  • The bad side with this answer - it returns an object - not a nice native array. – Yitzchak Oct 10 '21 at 09:48
  • 1
    @Yitzchak just `numArray = [...numArray]` if you need plain array. – dy_ Oct 13 '21 at 00:08
  • It even supports infinities and `NaN`! – wjandrea Oct 14 '21 at 20:52
  • This is both more efficient and more elegant. by now this is supported by all browsers, time to change the accepted answer for a better web. @peirix – JAR.JAR.beans Dec 30 '21 at 13:12
  • This is the right answer. – Jon Jan 08 '22 at 19:47
  • This solution may be faster but has a narrower versatility. I have a case where, the data to be sorted is an array of object which contains some ids (integer). like [{id: 1}, {id:2}, ..] In this case you can't convert the array this way and still the only solution is use a custom function – Federico Baù May 08 '22 at 08:25
  • 1
    Funny how a bunch of people discuss performance here without (a) providing a runnable benchmark, (b) stating the browser / engine / OS / processor they are using and (c) providing any measured timings (averaged over many runs, also making null-hypothesis testing) – Jonas Wilms Mar 01 '23 at 19:42
  • Good answer. I didn't know the typed arrays in JS. – Lucio Mollinedo Mar 24 '23 at 18:03
  • "really slow"... – tim-phillips May 19 '23 at 02:47
85

array.sort does a lexicographic sort by default, for a numeric sort, provide your own function. Here's a simple example:

function compareNumbers(a, b)
{
    return a - b;
}

numArray.sort(compareNumbers);

Also note that sort works "in place", there's no need for the assignment.

Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
  • 5
    I didn't understand above code, how does "return a - b" does the ascending sorting ? – vikramvi Jul 08 '19 at 06:58
  • 4
    if a < b, compareNumbers returns a negative number. If a > b, it will be positive. If equal, it returns 0. – Paul Dixon Jul 08 '19 at 14:01
  • 3
    @AliMertCakar because it only returns true or false, and the comparison function needs to return either a negative number, zero or a positive number. – Paul Dixon Sep 28 '20 at 13:54
75

This answer is equivalent to some of the existing answers, but ECMAScript 6 arrow functions provide a much more compact syntax that allows us to define an inline sort function without sacrificing readability:

numArray = numArray.sort((a, b) => a - b);

It is supported in most browsers today.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jjjjs
  • 1,500
  • 13
  • 9
38

just do .sort((a, b) => a - b) instead of .sort() itself. In addition to that the array is sorted in place. So return value does not matter.

var numArray = [140000, 104, 99];
numArray.sort((a, b) => a - b);
console.log(numArray)
Welcor
  • 2,431
  • 21
  • 32
norbekoff
  • 1,719
  • 1
  • 10
  • 21
34

The reason why the sort function behaves so weird

From the documentation:

[...] the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

If you print the unicode point values of the array then it will get clear.

console.log("140000".charCodeAt(0));
console.log("104".charCodeAt(0));
console.log("99".charCodeAt(0));

//Note that we only look at the first index of the number "charCodeAt(  0  )"

This returns: "49, 49, 57".

49 (unicode value of first number at 140000)
49 (unicode value of first number at 104)
57 (unicode value of first number at 99)

Now, because 140000 and 104 returned the same values (49) it cuts the first index and checks again:

console.log("40000".charCodeAt(0));
console.log("04".charCodeAt(0));

//Note that we only look at the first index of the number "charCodeAt(  0  )"
52 (unicode value of first number at 40000)
40 (unicode value of first number at 04)

If we sort this, then we will get:

40 (unicode value of first number at 04)
52 (unicode value of first number at 40000)

so 104 comes before 140000.

So the final result will be:

var numArray = [140000, 104, 99];
numArray = numArray.sort();
console.log(numArray)

104, 140000, 99

Conclusion:

sort() does sorting by only looking at the first index of the numbers. sort() does not care if a whole number is bigger than another, it compares the value of the unicode of the digits, and if there are two equal unicode values, then it checks if there is a next digit and compares it as well.

To sort correctly, you have to pass a compare function to sort() like explained here.

Black
  • 18,150
  • 39
  • 158
  • 271
  • Hint: This is only my explanation, I did not actually looked up the code. So don't fully trust this answer. – Black May 31 '19 at 09:19
21

Ascending

arr.sort((a, b) => a - b);

Descending

arr.sort((a, b) => b - a);

Just for fun:

Descending = Ascending + Reverse

arr.sort((a, b) => a - b).reverse();
R.M. Reza
  • 725
  • 1
  • 8
  • 20
15

I agree with aks, however instead of using

return a - b;

You should use

return a > b ? 1 : a < b ? -1 : 0;
  • 27
    Can you explain why anyone _should_ use your more unreadable ternary operation? As far as I can tell it would have the same result. – stefannew Jan 16 '15 at 17:05
  • 7
    This answer also takes equal values into consideration and leaves them in the same place. – Maarten00 Feb 03 '15 at 18:57
  • well, even though this answer doesn't contribute anything esle to the topic it doesn't deserve to get -1. All in all it is a valid answer, redendant but valid. – Celdor Aug 07 '15 at 08:12
  • 16
    "return a-b" may be adequate for the particular case of this question (javascript, and all input items known to be ints), but personally I prefer the ternary form because it's more canonical-- it works in more cases, in more programming languages, with more data types. E.g. in C, a-b can overflow, leading to the sort endless looping, corrupting memory, crashing, etc. That said, even the ternary form isn't going to work sanely if there are NaNs or mixed types involved. – Don Hatch Dec 08 '15 at 00:21
  • 12
    The `>` and `<` still compare a and b as strings. – vriesdemichael Nov 18 '16 at 11:58
  • Maybe a minor quibble, but: In javascript, there's only one numeric type; everything is a float. – Nate Dec 21 '16 at 18:00
  • 1
    `return +(a > b) || -(a < b);` – 7vujy0f0hy Apr 02 '17 at 13:09
  • 6
    @stefannew There is one case where this answer returns the correct evaluation for numbers where `a - b` doesnt. Where `a = b = -Infinity`, `a - b = NaN`, but the ternary returns `0`. But this doesn't seem to affect the sort, it still does it perfectly. `(a > b) - (a < b)` is a shorter version that is equivalent to this ternary. – Artyer Apr 15 '17 at 20:54
  • @vriesdemichael no they don't? – Roman Starkov Nov 09 '17 at 22:42
  • @RomanStarkov the point was that neither `ab` coerces the string elements into numbers whereas `a-b` does. – wOxxOm Oct 17 '18 at 19:33
  • @vriesdemichael @wOxxom I don't think `a` or `b` are strings in the sort fn; e.g. `[101, 3, -15].sort((a, b) => { console.log(typeof a); return a - b })` outputs `number` some number of times (depending on the browser) and sorts the values correctly. – Kevin Ji Nov 19 '18 at 02:27
  • This version works just as well with strings (`"a" - "b"` is `NaN`, but string comparisons with `<` and `>` work as expected). – Eric Ferreira Aug 14 '23 at 20:16
15

Array.sort uses alphabetic sorting by default instead of numeric .

To support numbers, add like following

var numArray = [140000, 104, 99];
numArray.sort((a, b) =>  a - b); // <-- Ascending
numArray.sort((a, b) =>  b - a); // <-- Descending
console.log(numArray);

OUTPUT :

Array Numeric Sorting

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
13

The question has already been answered, the shortest way is to use sort() method. But if you're searching for more ways to sort your array of numbers, and you also love cycles, check the following

Insertion sort

Ascending:

var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length; i++) {
    var target = numArray[i];
    for (var j = i - 1; j >= 0 && (numArray[j] > target); j--) {
        numArray[j+1] = numArray[j];
    }
    numArray[j+1] = target
}
console.log(numArray);

Descending:

var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length; i++) {
    var target = numArray[i];
    for (var j = i - 1; j >= 0 && (numArray[j] < target); j--) {
        numArray[j+1] = numArray[j];
    }
    numArray[j+1] = target
}
console.log(numArray);

Selection sort:

Ascending:

var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length - 1; i++) {
    var min = i;
    for (var j = i + 1; j < numArray.length; j++) {
        if (numArray[j] < numArray[min]) {
            min = j;
        }
    }
    if (min != i) {
        var target = numArray[i];
        numArray[i] = numArray[min];
        numArray[min] = target;
    }
}
console.log(numArray);

Descending:

var numArray = [140000, 104, 99];
for (var i = 0; i < numArray.length - 1; i++) {
    var min = i;
    for (var j = i + 1; j < numArray.length; j++) {
        if (numArray[j] > numArray[min]) {
            min = j;
        }
    }
    if (min != i) {
        var target = numArray[i];
        numArray[i] = numArray[min];
        numArray[min] = target;
    }
}
console.log(numArray);

Have fun

P.S.
  • 15,970
  • 14
  • 62
  • 86
  • Are any of these *actually* faster for tiny arrays than using `sort()` on a TypedArray like [this answer suggests](https://stackoverflow.com/a/53355543/224132). Certainly they won't be faster for medium to large arrays because these are O(n^2) algorithms. – Peter Cordes Nov 20 '19 at 04:43
12

In JavaScript the sort() method's default behaviour is to sort values in an array alphabetically.

To sort by number you have to define a numeric sort function (which is very easy):

...
function sortNumber(a, b)
{
  return a - b;
}

numArray = numArray.sort(sortNumber);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
9

Array.prototype.sort() is the go to method for sorting arrays, but there are a couple of issues we need to be aware of.

The sorting order is by default lexicographic and not numeric regardless of the types of values in the array. Even if the array is all numbers, all values will be converted to string and sorted lexicographically.

So should we need to customize the sort() and reverse() method like below.

Referred URL

For sorting numbers inside the array

numArray.sort(function(a, b)
{
    return a - b;
});

For reversing numbers inside the array

numArray.sort(function(a, b)
{
    return b - a;
});

Referred URL

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Merbin Joe
  • 611
  • 6
  • 27
7

The function 'numerically' below serves the purpose of sorting array of numbers numerically in many cases when provided as a callback function:

function numerically(a, b){
    return a-b;
}

array.sort(numerically); 

But in some rare instances, where array contains very large and negative numbers, an overflow error can occur as the result of a-b gets smaller than the smallest number that JavaScript can cope with.

So a better way of writing numerically function is as follows:

function numerically(a, b){
   if(a < b){
      return -1;
   } else if(a > b){
      return 1;
   } else {
      return 0;
   }
}
stackphish
  • 143
  • 3
  • 8
  • 1
    JavaScript numbers are floating-point. IEEE754 defines overflow and underflow rules, including overflow to +-Infinity, and underflow to subnormal or +-0.0. I don't think subtraction of two numbers can underflow to +-0.0 even if they're both large and nearby equal. The difference between two doubles is always representable as another non-zero double (unless it overflows, like `DBL_MIN - DBL_MAX`) but underflow isn't possible. Catastrophic cancellation makes the result imprecise, losing most of its "significant digits", but **`a-b` will always be non-zero and have the right sign for a!=b.** – Peter Cordes Nov 20 '19 at 04:49
6

to handle undefined, null, and NaN: Null behaves like 0, NaN and undefined goes to end.

array = [3, 5, -1, 1, NaN, 6, undefined, 2, null]
array.sort((a,b) => isNaN(a) || a-b)
// [-1, null, 1, 2, 3, 5, 6, NaN, undefined]
Ali Khosro
  • 1,580
  • 18
  • 25
  • 1
    The language spec requires that the compare function always return a number other than NaN when called on any two elements of the array. This function returns NaN when b is NaN or undefined, and when a and b are both Infinity or both -Infinity. – Adam M. Costello Jul 20 '21 at 05:44
  • The idea to check for NaN is not bad but this code doesn't put NaNs to the end – Konstantin Smolyanin Sep 30 '21 at 15:29
5

The accepted answer and equivalents like numArray.sort((a,b) => a - b) are great when the array contains only numbers without infinities or NaN. They can be extended to handle infinities and NaN like so:

numArray.sort((a,b) => (+a || 0) - (+b || 0) || 0);

This sorts NaN (or any non-number, like 'foo' or {}) as if it were 0. The final || 0 is needed to handle the case where a and b are equal infinities.

4

While not required in JavaScript, if you would like the sort() compareFunction to strictly return -1, 0, or 1 (similar to how the spaceship operator works in PHP), then you can use Math.sign().

The compareFunction below strictly returns -1, 0, or 1:

numArray.sort((a, b) => Math.sign(a - b));

Note: Math.sign() is not supported in Internet Explorer.

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
3

For a normal array of elements values only:

function sortArrayOfElements(arrayToSort) {
    function compareElements(a, b) {
        if (a < b)
            return -1;
        if (a > b)
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareElements);
}

e.g. 1:
var array1 = [1,2,545,676,64,2,24]
**output : [1, 2, 2, 24, 64, 545, 676]**

var array2 = ["v","a",545,676,64,2,"24"]
**output: ["a", "v", 2, "24", 64, 545, 676]**

For an array of objects:

function sortArrayOfObjects(arrayToSort, key) {
    function compareObjects(a, b) {
        if (a[key] < b[key])
            return -1;
        if (a[key] > b[key])
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareObjects);
}

e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]

**output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]**
Umesh
  • 941
  • 5
  • 12
3

In order to create this kind of sort, you have to pass a function that will check which comes first.

define inside the function which value do you wanna check: a.id - a.id

        const myJson = [
            { id: 1, name: 'one'},
            { id: 4, name: 'four'},
            { id: 2, name: 'two'},
            { id: 3, name: 'three'}
        ];

        // provide the sort method to check
        const myNewSort = myJson.sort(function(a, b) {
          return a.id - b.id;
        });

        console.log('my new sort',myNewSort)
Coffezilla
  • 376
  • 2
  • 7
2

Update! Scroll to bottom of answer for smartSort prop additive that gives even more fun!
Sorts arrays of anything!

My personal favorite form of this function allows for a param for Ascending, or Descending:

function intArraySort(c, a) {
    function d(a, b) { return b - a; }
    "string" == typeof a && a.toLowerCase();
    switch (a) {
        default: return c.sort(function(a, b) { return a - b; });
        case 1:
                case "d":
                case "dc":
                case "desc":
                return c.sort(d)
    }
};

Usage as simple as:

var ara = function getArray() {
        var a = Math.floor(Math.random()*50)+1, b = [];
        for (i=0;i<=a;i++) b.push(Math.floor(Math.random()*50)+1);
        return b;
    }();

//    Ascending
intArraySort(ara);
console.log(ara);

//    Descending
intArraySort(ara, 1);
console.log(ara);

//    Ascending
intArraySort(ara, 'a');
console.log(ara);

//    Descending
intArraySort(ara, 'dc');
console.log(ara);

//    Ascending
intArraySort(ara, 'asc');
console.log(ara);

jsFiddle


Or Code Snippet Example Here!

function intArraySort(c, a) {
 function d(a, b) { return b - a }
 "string" == typeof a && a.toLowerCase();
 switch (a) {
  default: return c.sort(function(a, b) { return a - b });
  case 1:
  case "d":
  case "dc":
  case "desc":
  return c.sort(d)
 }
};

function tableExample() {
 var d = function() {
   var a = Math.floor(50 * Math.random()) + 1,
    b = [];
   for (i = 0; i <= a; i++) b.push(Math.floor(50 * Math.random()) + 1);
   return b
  },
  a = function(a) {
   var b = $("<tr/>"),
    c = $("<th/>").prependTo(b);
   $("<td/>", {
    text: intArraySort(d(), a).join(", ")
   }).appendTo(b);
   switch (a) {
    case 1:
    case "d":
    case "dc":
    case "desc":
     c.addClass("desc").text("Descending");
     break;
    default:
     c.addClass("asc").text("Ascending")
   }
   return b
  };
 return $("tbody").empty().append(a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1))
};

tableExample();
table { border-collapse: collapse; }
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }
.asc { color: red; }
.desc { color: blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table><tbody></tbody></table>

.smartSort('asc' | 'desc')

Now have even more fun with a sorting method that sorts an array full of multiple items! Doesn't currently cover "associative" (aka, string keys), but it does cover about every type of value! Not only will it sort the multiple values asc or desc accordingly, but it will also maintain constant "position" of "groups" of values. In other words; ints are always first, then come strings, then arrays (yes, i'm making this multidimensional!), then Objects (unfiltered, element, date), & finally undefineds and nulls!

"Why?" you ask. Why not!

Now comes in 2 flavors! The first of which requires newer browsers as it uses Object.defineProperty to add the method to the Array.protoype Object. This allows for ease of natural use, such as: myArray.smartSort('a'). If you need to implement for older browsers, or you simply don't like modifying native Objects, scroll down to Method Only version.

/* begin */
/* KEY NOTE! Requires EcmaScript 5.1 (not compatible with older browsers) */
;;(function(){if(Object.defineProperty&&!Array.prototype.smartSort){var h=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a>b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("a");b instanceof Array&&b.smartSort("a");if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("a"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("a"),a.id==e[0]?1:-1;e=[a.tagName, b.tagName].smartSort("a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("a"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d"); return a[d].tagName==c[0]?1:-1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]>g[1]},k=function(a,b){if(null== a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("d");b instanceof Array&&b.smartSort("d");if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("d"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("d"),a.id==e[0]?-1:1;e=[a.tagName,b.tagName].smartSort("d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("d"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1;if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]};Object.defineProperty(Array.prototype,"smartSort",{value:function(){return arguments&& (!arguments.length||1==arguments.length&&/^a([sc]{2})?$|^d([esc]{3})?$/i.test(arguments[0]))?this.sort(!arguments.length||/^a([sc]{2})?$/i.test(arguments[0])?h:k):this.sort()}})}})();
/* end */

jsFiddle Array.prototype.smartSort('asc|desc')


Use is simple! First make some crazy array like:

window.z = [ 'one', undefined, $('<span />'), 'two', null, 2, $('<div />', { id: 'Thing' }), $('<div />'), 4, $('<header />') ];
z.push(new Date('1/01/2011'));
z.push('three');
z.push(undefined);
z.push([ 'one', 'three', 'four' ]);
z.push([ 'one', 'three', 'five' ]);
z.push({ a: 'a', b: 'b' });
z.push({ name: 'bob', value: 'bill' });
z.push(new Date());
z.push({ john: 'jill', jack: 'june' });
z.push([ 'abc', 'def', [ 'abc', 'def', 'cba' ], [ 'cba', 'def', 'bca' ], 'cba' ]);
z.push([ 'cba', 'def', 'bca' ]);
z.push({ a: 'a', b: 'b', c: 'c' });
z.push({ a: 'a', b: 'b', c: 'd' });

Then simply sort it!

z.smartSort('asc'); // Ascending
z.smartSort('desc'); // Descending

Method Only

Same as the preceding, except as just a simple method!

/* begin */
/* KEY NOTE! Method `smartSort` is appended to native `window` for global use. If you'd prefer a more local scope, simple change `window.smartSort` to `var smartSort` and place inside your class/method */
window.smartSort=function(){if(arguments){var a,b,c;for(c in arguments)arguments[c]instanceof Array&&(a=arguments[c],void 0==b&&(b="a")),"string"==typeof arguments[c]&&(b=/^a([sc]{2})?$/i.test(arguments[c])?"a":"d");if(a instanceof Array)return a.sort("a"==b?smartSort.asc:smartSort.desc)}return this.sort()};smartSort.asc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a> b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.asc);b instanceof Array&&b.sort(smartSort.asc);if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c], b[c]],"a"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"a"),a.id==e[0]?1:-1;e=smartSort([a.tagName,b.tagName],"a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g), "a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"a"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"a");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1; if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==c[0]?1:-1}g=[a,b].sort();return g[0]>g[1]};smartSort.desc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)? 1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.desc);b instanceof Array&&b.sort(smartSort.desc);if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c],b[c]],"d"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]], b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"d"),a.id==e[0]?-1:1;e=smartSort([a.tagName,b.tagName],"d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g),"a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&& b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"d"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1; if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]}
/* end */

Use:

z = smartSort(z, 'asc'); // Ascending
z = smartSort(z, 'desc'); // Descending

jsFiddle Method smartSort(Array, "asc|desc")

SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
2

Try this code:

HTML:

<div id="demo"></div>

JavaScript code:

<script>
    (function(){
        var points = [40, 100, 1, 5, 25, 10];
        document.getElementById("demo").innerHTML = points;
        points.sort(function(a, b){return a-b});
        document.getElementById("demo").innerHTML = points;
    })();
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sunny S.M
  • 5,768
  • 1
  • 38
  • 38
2

Try this code as below

var a = [5, 17, 29, 48, 64, 21];
function sortA(arr) {
return arr.sort(function(a, b) {
return a - b;
})
;} 
alert(sortA(a));
Marek Urbanowicz
  • 12,659
  • 16
  • 62
  • 87
2

TypeScript variant

const compareNumbers = (a: number, b: number): number => a - b

myArray.sort(compareNumbers)
Chris Kobrzak
  • 1,044
  • 14
  • 20
1

You can sort number array simply by

const num=[13,17,14,19,16];
let temp;
for(let i=0;i<num.length;i++){
    for(let j=i+1;j<num.length;j++){
        if(num[i]>num[j]){
            temp=num[i]
            num[i]=num[j]
            num[j]=temp
        }
    }
}

console.log(num);
fcdt
  • 2,371
  • 5
  • 14
  • 26
1

You can get height and lowest number simply by using max() and min() in-built function

var numArray = [140000, 104, 99];
console.log(Math.max(...numArray));
console.log(Math.min(...numArray));

If you want to sort in ascending or descending order

numArray.sort((a, b)=> a - b);

Know more

MD SHAYON
  • 7,001
  • 45
  • 38
1

let grade =[80,100,50,90,40];
grade.sort((x,y)=> x-y);
grade.forEach(element=>console.log(element));
twizelissa
  • 111
  • 5
0

As sort method converts Array elements into string. So, below way also works fine with decimal numbers with array elements.

let productPrices = [10.33, 2.55, 1.06, 5.77];
console.log(productPrices.sort((a,b)=>a-b));

And gives you the expected result.

0

Sort integers > 0, think outside the box:

function sortArray(arr) {
  return new Promise((resolve) => {
    const result = []
    arr.forEach((item) => {
      setTimeout(() => {
        result.push(item)
        if (result.length === arr.length) resolve(result)
      }, item)
    })
  })
}

sortArray([4, 2, 42, 128, 56, 2]).then((result) => {
  document.write(JSON.stringify(result))
})

Note that this should not be used productively, .sort() is better suited for this, check the other answers

Putzi San
  • 5,566
  • 3
  • 19
  • 35
0

sort_mixed

Object.defineProperty(Array.prototype,"sort_mixed",{
    value: function () { // do not use arrow function
        var N = [], L = [];
        this.forEach(e => {
            Number.isFinite(e) ? N.push(e) : L.push(e);
        });
        N.sort((a, b) => a - b);
        L.sort();
        [...N, ...L].forEach((v, i) => this[i] = v);
        return this;
    })

try a =[1,'u',"V",10,4,"c","A"].sort_mixed(); console.log(a)

bortunac
  • 4,642
  • 1
  • 32
  • 21
0

If anyone doesn't understand how Array.sort() works with integers, read this answer.

Alphabetical order:

By default, the sort() method sorts the values as strings in alphabetical and ascending order.

const myArray = [104, 140000, 99];
myArray.sort();
console.log(myArray); // output is [104, 140000, 99]

Ascending order with array.sort(compareFunction):

const myArray = [104, 140000, 99];
myArray.sort(function(a, b){
  return a - b;
});
console.log(myArray); // output is [99, 104, 140000]

Explanation from w3schools:

compareFunction defines an alternative sort order. The function should return a negative, zero, or positive value, depending on the arguments, like: function(a, b){return a-b} When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

Example:

When comparing 40 and 100, the sort() method calls the compare function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

The sort function will sort 40 as a value lower than 100.

Descending order with array.sort(compareFunction):

const myArray = [104, 140000, 99];
myArray.sort(function(a, b){
  return b - a;
});
console.log(myArray); // output is [140000, 104, 99]

This time we calculated with b - a(i.e., 100-40) which returns a positive value.

Mejan
  • 918
  • 13
  • 18
0

If you need to calculate and sort the largest charCodeAt from a list of string this is the right way.

const arrayLines = '1.1.1.1\n1.0.1.1\n1.1.1.2\n1.1.1.0'.split('\n');

// Response: (4) ['1.0.1.1', '1.1.1.0', '1.1.1.1', '1.1.1.2']
arrayLines.sort((a, b) => {
    let a_charCodeSize = 0,
        b_charCodeSize = 0;

    // Loop true a & b characters and calculate the charCodeAt size.
    for (const aChar of a) a_charCodeSize += aChar.charCodeAt(0);
    for (const bChar of b) b_charCodeSize += bChar.charCodeAt(0);

    return a_charCodeSize - b_charCodeSize;
});
Tesla
  • 169
  • 1
  • 6
  • why the need to write any implementation, javascript sort natively does exactly same thing, it compares strings by their character code from starting index and moves forward. arrayLines.sort() responses same way, without passing any custom function – Sajid Ali Jan 21 '22 at 17:16
  • @SajidAli Natively sort does not compare all characters one by one but instead evaluate the whole value given. Which will not result in a correct response in that scenario. – Tesla Jan 24 '22 at 08:46
  • try native sort in above example and see... sort() sorts the elements of array in place and returns sorted array. Default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values If function is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. ref: MDN – Sajid Ali Feb 07 '22 at 12:29
  • @SajidAli i tried it but it doesn't produce the desired output. sort using a-b is returning ['1.1.1.1', '1.0.1.1', '1.1.1.2', '1.1.1.0'] which makes no sense. – Tesla Feb 09 '22 at 06:15
  • that's your problem right there. no need to add a-b at all, just use sort without passing any callback function. arrayLines.sort(), and it will show you same result as you got by implementing your own custom callback method – Sajid Ali Mar 29 '22 at 19:54
-1
  1. Ascending

    const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];

If we return something < 0 then A will be before B If we return something > 0 then B will be before A

 movements.sort((a, b) => {
      if (a > b) return 1; //- (Switch order)
      if (a < b) return -1; //- (Keep order)
    });

a - current value, b - the next value.

  1. Descending

    movements.sort((a, b) => { if (a > b) return -1; // - (Keep) if (a < b) return 1; // - (Switch) });

! Improve, best solution !

movements.sort ((a, b) => a - b); // Same result!

If a < b it's negative number(Switch) If a < b it's negative number(Keep)

vitoboski
  • 203
  • 2
  • 3
  • Your last bit has a typo, leading to a oxymoron. Your first bit does not address the situation where a==b. To format inline code, isurrounded it by single backtics. – SherylHohman Apr 21 '21 at 19:00