Sort Array Method Javascript
-
Method used to sort elements of an array in place.
-
Mutates the array
-
Sorts elements as strings in lexicographic order (UTF-16 encoding), not alphabetical order
-
lexicographic = (alphabet + numbers + symbols) as strings
-
(a, b) => a-b
-
if
; a, b -
if
; b, a -
if
; order is not changed -
Sorting array of object with a string property
- (a, b) => a.title.localeCompare(b.title)
-
Returns the reference to the original array on which the
sortmethod is called
let nums = [1, 2, 10, 5, 4, 3];
nums.sort();
console.log(nums); // [1, 10, 2, 3, 4, 5]
nums.sort((a, b) => a - b);
console.log(nums); // [1, 2, 3, 4, 5, 10]
let x = nums.sort((a, b) => b - a);
console.log(x); // [10, 5, 4, 3, 2, 1]
x[0] = 30;
console.log(x); // [30, 5, 4, 3, 2, 1]