1

I want to learn how the sort() method works in JavaScript, I know that sort has a default function for comparison but I want to pass a function and understand how it processes the function.

I want to sort the following array ["a", "d", "c", "a", "z", "g"] alphabetically, but when I use the method arr.sort((a,b) => a>b); returns the same array without sorting.

Please, anyone can explain to me this.

I'm learning JavaScript and trying to understand the methods in the arrays, like map(), reduce() and filter() but I get stuck in the sort() method.

let arr = ["a", "d", "c", "a", "z", "g"];
console.log(arr.sort((a,b) => a>b));

the result is ["a", "d", "c", "a", "z", "g"], but I want ["a", "a", "c", "d", "g", "z"].

And I know if I use the sort() method without arguments the algorithm sort it but I want to understand why it's not working with argument.

Esteban Camargo
  • 63
  • 1
  • 14
  • 5
    See this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description – Dacre Denny Sep 03 '19 at 23:15
  • `arr.sort((a,b) => a.localeCompare(b));` – ASDFGerte Sep 03 '19 at 23:39
  • The method expecting a difference and not a Boolean value, but you can call the method without argument: `console.log(arr.sort());` – mars073 Sep 04 '19 at 01:16
  • Gracias por sus comentarios, con la función localeCompare() tuve unos problemas con mi objetivo, ya que 'b'.localeCompare('A') me devuelve 1, y estaba buscando que se relacionara a los ASCII, lo que mejor me funcionó fue esto: arr.sort( (b,a) => a.charCodeAt() - b.charCodeAt() ) – Esteban Camargo Mar 31 '20 at 20:35

3 Answers3

3

Your function is returning a boolean, but should be returning a number. Let's see what happens to your boolean value when converted to a number:

console.log((3>2)+0); // returns 1
console.log((3==2)+0); // returns 0
console.log((3<2)+0); // returns 0

So, when a == b and when a > b, you end up with the same integer value.

The underlying problem is that you need a function instead that returns THREE possible values, 0, -1 and 1.

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
2

let arr = ["a", "d", "c", "a", "z", "g"];
document.querySelector("#sorted").innerHTML = arr.sort((a, b) => {

 if (a > b) {
    return 1;
  } else if (a < b) {
    return -1;
  } else {
    return 0;
  }
}).join(", ");
<div id="sorted"></div>

When you sort, there are essentially a number of comparisons happening with the sorting algorithm selected (mergesort, quicksort, etc...), to place items in specific positions. See array sorting on mdn

Default comparisons may not work for all cases. For that you can provide a comparison function to explicitly state how you want to compare two items. You will have to specify if item 1 should appear before/after/adjacent to item 2 based on some arbitrary criteria. (You are looking for lexical placement). So in this case you have to specify all of those cases whereas you haven't specified that including case for equals.

So the following should get you what you want.

let arr = ["a", "d", "c", "a", "z", "g"];
console.log(arr.sort((a, b) => {

 if (a > b) {
    return 1;
  } else if (a < b) {
    return -1;
  } else {
    return 0;
  }
}));
santon
  • 1,654
  • 16
  • 26
0

Hi if you are using a custom function, then will expected to return a negative number, or zero, or positive value, like:

0, 1 or -1

When you return 0 that is means that A value is === than B (no changes expected ) When you return a negative number like -1 The sort function will sort A as a value lower than B. When you return a positive number like 1 then the sort function will sort A as a value higher than B.

Lucas Matos
  • 2,531
  • 2
  • 15
  • 17