.sort alphanumeric
https://stackoverflow.com/questions/4340227/sort-mixed-alpha-numeric-array
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true }) console.log(['A1', 'A10', 'A11', 'A12', 'A2', 'A3', 'A4', 'B10', 'B2', 'F1', 'F12', 'F3'].sort(sortAlphaNum))
localCompcare
https://www.w3schools.com/jsref/jsref_localecompare.asp
The localeCompare() method compares two strings in the current locale.
The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).
.sort( (a,b) => a-b)
https://forum.freecodecamp.org/t/arr-sort-a-b-a-b-explanation/167677
When you sort an array with .sort(), it assumes that you are sorting strings. When sorting numbers, the default behavior will not sort them properly.
The function that you pass tells how to sort the elements. It takes two parameters (a and b) that represent any two elements from the array. How the elements will be sorted depends on the function’s return value:
- if it returns a negative value, the value in
awill be ordered beforeb. - if it returns
0, the ordering ofaandbwon’t change. - if it returns a positive value, the value in
bwill be ordered beforea.
When you pass the function (a, b) => a - b, you’re telling the .sort() function to sort the numbers in ascending order.
No comments:
Post a Comment