简体   繁体   中英

Sorting an array by returning 1 or 0 or -1 if it returns these values how the sort function can decide which one to put first

I don't understand the logic of sorting an array by returning 1 or 0 or -1 if it returns these values how the sort function can decide which one to put first

Example Let say we have an array

 const newArray = [5.55, 4.3, 3.4, 1.8, 2.5]; const modifiedArray = newArray.sort((a, b) => { if (a > b) { return 1; } else if (a === b) { return 0; } else { return -1; } }); console.log(modifiedArray);

The MDN documentation states it like this:

  • If your compare function returns -1 then it places a before b.
  • If it returns 1 then it places b before a.
  • If it returns 0 then the order remains unchanged.

By the way, the compare function does not have to return exactly -1 or 1 but only values that are smaller or greater than 0. So it would be possible to sort an array in ascending order like this:

var sortedArray = [1,0,5].sort((a,b) => a-b);

According to the docs

If compareFunction(a, b) returns less than 0, sort a to an index lower than b (ie a comes first).

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAScript standard only started guaranteeing this behavior in 2019, thus, older browsers may not respect this.

If compareFunction(a, b) returns greater than 0, sort b to an index lower than a (ie b comes first).

if you put log inside your modifiedArray() function, you can see that the same number is compared again but with other numbers.

You can also read about sort algorithms like "quick sort" and etc.

The (a,b) is a compare function which we pass in sort. Consider the following example:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort();
console.log(numbers);

The output is:
[ 0, 1, 10, 2, 20, 3, 30 ]

So to fix the above issue we pass (a,b) for sorting.

If compare(a,b) is less than zero, the sort() method sorts a to a lower index than b. In other words, a will come first. If compare(a,b) is greater than zero, the sort() method sort b to a lower index than a, ie, b will come first. If compare(a,b) returns zero, the sort() method considers a equals b and leaves their positions unchanged.

If you want to know more about sort in js in details: https://www.javascripttutorial.net/javascript-array-sort/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM