Last active
March 29, 2022 20:19
-
-
Save macmcmeans/833d5133ef8a5087e25a85e442fbfb1a to your computer and use it in GitHub Desktop.
JavaScript Natural Sort (strings, integers, decimals, nested arrays)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Perform a natural sort respecting integers, decimals, nested arrays and embedded digits in strings. | |
This version sorts US currency as decimals. | |
SO: https://stackoverflow.com/questions/14599321/javascript-natural-sort/71621852#71621852 | |
*/ | |
let items = [1, 0.99, '1.22', 1.24, '3rd', 12, '$1.23', 99, '24th', '99 in the shade', 'B', 'Dec', 400.23, '10000', '101', 'a', [2,3,4], 'Apple', 'apple.sauce', 'Dec3', 'Dec20', 'house11a', 'house11b', 'house', 'house99']; | |
items.sort( ( a, b ) => ( ( a + '' ).substr( 0, 1 ) === '$' ? ( a + '' ).substr(1, (a + '' ).length ) : ( a + '' ) ).localeCompare( b, 'en', { ignorePunctuation: true, numeric: true, sensitivity: 'base' } ) ); | |
/* | |
OUPUT: | |
> [0.99, 1, '1.22', '$1.23', 1.24, Array(3), '3rd', 12, '24th', 99, '99 in the shade', '101', 400.23, '10000', 'a', 'Apple', 'apple.sauce', 'B', 'Dec', 'Dec3', 'Dec20', 'house', 'house11a', 'house11b', 'house99'] | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment