Sort an array that has a hyphen in javascript

I want to update this sorted result in javascript.

A1-1, A1-3, A1-3-1, A1-4, A2, A4-1, A6-3, A13-1, A13-2, A13-3, A13-11, A13-14, A51- 2

But I have the following result with this code.

sortedAlphabetListData.sort(
  function(a,b){
    if( a[0] < b[0] ) return -1;
    if( a[0] > b[0] ) return 1;
    return 0;
  }
);

A1-1, A1-3, A1-3-1, A1-4, A13-1, A13-11, A13-14, A13-2, A13-3, A2, A4-1, A51-2, A6- 3

I tried this library. https://gist.github.com/think49/660141 But this did not work. “A23” came first, and “A3-1” came after.

I read this post and tried it. Javascript: natural looking alphanumeric strings

var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var sortedAlphabetListData = alphabetListData.sort(collator.compare);

But it only works on IE11 and does not work on Safari. I need to support IE9 and safari.

I need your help. Thank!

+4
source
1

cusstom sort, .

function customSort(data, order) {

    function isNumber(v) {
        return (+v).toString() === v;
    }

    var sort = {
            asc: function (a, b) {
                var i = 0,
                    l = Math.min(a.value.length, b.value.length);

                while (i < l && a.value[i] === b.value[i]) {
                    i++;
                }
                if (i === l) {
                    return a.value.length - b.value.length;
                }
                if (isNumber(a.value[i]) && isNumber(b.value[i])) {
                    return a.value[i] - b.value[i];
                }
                return a.value[i].localeCompare(b.value[i]);
            },
            desc: function (a, b) {
                return sort.asc(b, a);
            }
        },
        mapped = data.map(function (el, i) {
            var string = el.replace(/\d(?=[a-z])|[a-z](?=\.)/gi, '$&. .'),
                regex = /(\d+)|([^0-9.]+)/g,
                m,
                parts = [];

            while ((m = regex.exec(string)) !== null) {
                parts.push(m[0]);
            }
            return { index: i, value: parts, o: el, string: string };
        });

    mapped.sort(sort[order] || sort.asc);
    return mapped.map(function (el) {
        return data[el.index];
    });
}

var array = ['A1-1', 'A1-3', 'A1-3-1', 'A1-4', 'A2', 'A4-1', 'A6-3', 'A13-1', 'A13-2', 'A13-3', 'A13-11', 'A13-14', 'A51-2'];

console.log(customSort(array));
console.log(customSort(array, 'desc'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hide result
+2

Source: https://habr.com/ru/post/1688512/


All Articles