Page 110 - JavaScript
P. 110
Array.isArray has the an advantage over using a instanceof check in that it will still return true
even if the prototype of the array has been changed and will return false if a non-arrays prototype
was changed to the Array prototype.
var arr = [];
Object.setPrototypeOf(arr, null);
Array.isArray(arr); // true
arr instanceof Array; // false
Sorting Arrays
The .sort() method sorts the elements of an array. The default method will sort the array
according to string Unicode code points. To sort an array numerically the .sort() method needs to
have a compareFunction passed to it.
Note: The .sort() method is impure. .sort() will sort the array in-place, i.e., instead of
creating a sorted copy of the original array, it will re-order the original array and return
it.
Default Sort
Sorts the array in UNICODE order.
['s', 't', 'a', 34, 'K', 'o', 'v', 'E', 'r', '2', '4', 'o', 'W', -1, '-4'].sort();
Results in:
[-1, '-4', '2', 34, '4', 'E', 'K', 'W', 'a', 'l', 'o', 'o', 'r', 's', 't', 'v']
Note: The uppercase characters have moved above lowercase. The array is not in
alphabetical order, and numbers are not in numerical order.
Alphabetical Sort
['s', 't', 'a', 'c', 'K', 'o', 'v', 'E', 'r', 'f', 'l', 'W', '2', '1'].sort((a, b) => {
return a.localeCompare(b);
});
Results in:
['1', '2', 'a', 'c', 'E', 'f', 'K', 'l', 'o', 'r', 's', 't', 'v', 'W']
Note: The above sort will throw an error if any array items are not a string. If you know
that the array may contain items that are not strings use the safe version below.
['s', 't', 'a', 'c', 'K', 1, 'v', 'E', 'r', 'f', 'l', 'o', 'W'].sort((a, b) => {
return a.toString().localeCompare(b);
});
https://riptutorial.com/ 67

