-2

I know how or I thought I knew how sort worked in javascript. I know that by returning a-b, my array will be sorted ascending order.

However what is happening with this code, why do I not get the array in ascening order, instead I get the following

          var q = [1,2,3,4,5,6]

         q.sort((a,b)=>{return -1});
         [6, 5, 4, 3, 2, 1]
  • 1
    Does this answer your question? [How to sort an array of integers correctly](https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly) – Thimma Aug 15 '20 at 17:11

2 Answers2

1

Explanation:

By default, a sort () function does javascript in a lexical order in your Array. However, you can optionally pass a function in the input parameter, so that it returns the desired result.

About a sort () function:

** sort ** ([* sort function *] **) **

** Description: ** sort an array lexically by default, but a function can be passed for sorting.

Parameters:

** sortFunction ** (function) * optional *:

A function that returns the order needed to be used in sort ().

#Example:

    function sortfunction(a, b){
  return (a - b) //faz com que o array seja ordenado numericamente e de ordem crescente.
}
Data = [3,5,1,7,3,9,10];
alert(Data.sort(sortfunction));
0

You can do that using a utility function

function compareNumbers(a, b) {
  return b - a;
}
let q = [1,2,3,4,5,6]

q.sort(compareNumbers)
var q = [1,2,3,4,5,6]
  // [6, 5, 4, 3, 2, 1]


To sort in ascending order subtract b from a

Fritzdultimate
  • 372
  • 2
  • 11