re: 10 JavaScript array methods you should know VIEW POST

VIEW FULL DISCUSSION
 

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

Thanks for that buddy, i didn't know that .sort() without passing callback it sort element in ascending order

const alpha = ['e', 'a', 'c', 'u', 'y'];
console.log(alpha.sort()); // output ["a", "c", "e", "u", "y"]

.. now here is problem

const nums = [3, 4, 21, 100];
console.log(nums.sort()); // output [100, 21, 3, 4]

// In opinion, should always do this
console.log(nums.sort((a, b) => a > b ? 1:-1)); // output [3, 4, 21, 100]
code of conduct - report abuse