Based on JS imitate the sorting effect of windows files by name
- 2021-07-01 06:20:22
- OfStack
Make a record, mainly for the processing of numbers. If the preceding characters of numbers are the same, the numbers are compared by value, not between individual characters.
function SortLikeWin(v1, v2) {
var a = v1.name;
var b = v2.name;
var reg = /[0-9]+/g;
var lista = a.match(reg);
var listb = b.match(reg);
if (!lista || !listb) {
return a.localeCompare(b);
}
for (var i = 0, minLen = Math.min(lista.length, listb.length) ; i < minLen; i++) {
// Number location serial number
var indexa = a.indexOf(lista[i]);
var indexb = b.indexOf(listb[i]);
// Prefix before number
var prefixa = a.substring(0, indexa);
var prefixb = a.substring(0, indexb);
// Digital string
var stra = lista[i];
var strb = listb[i];
// The value of a number
var numa = parseInt(stra);
var numb = parseInt(strb);
// If the serial numbers of numbers are not equal or the prefixes are not equal, the prefixes are different, and the comparison is made directly
if (indexa != indexb || prefixa != prefixb) {
return a.localeCompare(b);
}
else {
// Digital string Congruent
if (stra === strb) {
// If it is the last 1 Number, compare the suffix of the number
if (i == minLen - 1) {
return a.substring(indexa).localeCompare(b.substring(indexb));
}
// If it's not the last 1 Number, the loop jumps to the following 1 Number, and remove the same part before
else {
a = a.substring(indexa + stra.length);
b = b.substring(indexa + stra.length);
}
}
// If the number of string Incomplete equality, but equal values
else if (numa == numb) {
// Direct comparison of digital prefixes 0 The number of, much smaller
return strb.lastIndexOf(numb + '') - stra.lastIndexOf(numa + '');
}
else {
// If the numbers are not equal, compare the numbers directly
return numa - numb;
}
}
}
}
Usage, Array. sort (SortLikeWin);