DEV Community

Discussion on: 10 JavaScript array methods you should know

Collapse
 
zalithka profile image
Andre Greeff • Edited

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:

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']