by
5
7
4,521
5
Top 1% !
Popular
Famous
Nice
Easy-to-find
Specified
OpenSource
Popularity: 1997th place
Languagejavascript
LicenseMIT_X11

How to sort a Javascript array parsing elements using regex pattern

The Javascript Array.sort() method accepts a callback function to compare two elements of the array using a specific logic.
The callback function below may help you in sorting an array matching a particular regular expression pattern.

The format of elements in array is x/y/z, where x, y and z are integers, eg "5/10/2".
I need to sort the elements based on <integer_X> value at first, then if equals sorting on <integer_Y> and finally on <integer_Z>.

In the case the regex is not matching the pattern, the standard lexicographic sorting will be applied.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/191150/How-to-sort-a-Javascript-array-parsing-e?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
var myCompare = function(a,b) { var matchPattern_A = /^([0-9]+)\/([0-9]+)\/([0-9]+)$/g.exec(a); var matchPattern_B = /^([0-9]+)\/([0-9]+)\/([0-9]+)$/g.exec(b); if(matchPattern_A && matchPattern_B) { //Apply regex sort //I need to sort based on match[1], match[2], match[3] console.log('Apply regex sort'); if (parseInt(matchPattern_A[1], 10) < parseInt(matchPattern_B[1], 10)) return -1; if (parseInt(matchPattern_A[1], 10) > parseInt(matchPattern_B[1], 10)) return 1; else { if (parseInt(matchPattern_A[2], 10) < parseInt(matchPattern_B[2], 10)) return -1; if (parseInt(matchPattern_A[2], 10) > parseInt(matchPattern_B[2], 10)) return 1; else { if (parseInt(matchPattern_A[3], 10) < parseInt(matchPattern_B[3], 10)) return -1; if (parseInt(matchPattern_A[3], 10) > parseInt(matchPattern_B[3], 10)) return 1; return 0; } } } else { //Apply basic lexicographic sort console.log('Apply basic lexicographic sort'); if (a < b) return -1; if (a > b) return 1; return 0; } }; var myArr = [ '5/4/30', '5/10/2', '5/4/3', '1/3/8']; console.log(myArr); myArr.sort(this.myCompare); console.log(myArr); /* Example, having an array as ['5/4/30', '5/10/2', '5/4/3', '1/3/8'] it will be sorted as ['1/3/8', '5/4/3', '5/4/30', '5/10/2'] */
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus