There's one critical point of .sort() that I feel you should mention in the article: the .sort() method sorts an array in place, it does not return a sorted copy of the array...
.sort()
Basically, if you do the following:
const myThings = [5,2,4,3,6,1]; const sortedThings = myThings.sort();
..then both variables will contain the same thing:
myThings; // [1,2,3,4,5,6] sortedThings; // [1,2,3,4,5,6] myThings === sortedThings; // true
With this in mind, your example could be simplified to the following:
const arr = [1, 2, 3, 4, 5, 6]; const alpha = ['e', 'a', 'c', 'u', 'y']; // sort in descending order arr.sort((a, b) => a > b ? -1 : 1); console.log(arr); // output: [6, 5, 4, 3, 2, 1] // sort in ascending order alpha.sort((a, b) => a > b ? 1 : -1); console.log(alpha); // output: ['a', 'c', 'e', 'u', 'y']
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
There's one critical point of
.sort()
that I feel you should mention in the article: the.sort()
method sorts an array in place, it does not return a sorted copy of the array...Basically, if you do the following:
..then both variables will contain the same thing:
With this in mind, your example could be simplified to the following: