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.

4
  • 5
    See this: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 3, 2019 at 23:15
  • arr.sort((a,b) => a.localeCompare(b)); Commented Sep 3, 2019 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()); Commented Sep 4, 2019 at 1: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() ) Commented Mar 31, 2020 at 20:35

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I got it now, with my function I never going to get a negative value and sort don't work.
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;
  }
}));

1 Comment

That's it, thanks a lot.
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.

1 Comment

Oh thanks, that was my problem, my function doesn't return a negative number for that comparison.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.