Javascript: un altfel tip de sortare

Implementează cod, script-uri JavaScript pentru website. Cere soluții de la specialiști.
Avatar utilizator
specialist it
Mesaje: 205
Membru din: 28 Iun 2017, 16:39
6
Contact:

Javascript: un altfel tip de sortare

Mesaj de specialist it »

Salut,

Mai jos regăsiți un alt exemplu de cod creat pentru a customiza sortarea în JS:

Cod: Selectaţi tot

function customSort(arr) {
    var len = arr.length;
    for (var i = len - 1; i >= 0; i--) {
        for (var j = 1; j <= i; j++) {
            decArrJ0 = parseInt(arr[j - 1].split(".")[1]);
            decArrJ = parseInt(arr[j].split(".")[1]);

            if ((decArrJ0 > decArrJ)) {

            var temp = arr[j - 1];
            arr[j - 1] = arr[j];
            arr[j] = temp;
        }
    }

    for (var x = len - 1; x >= 0; x--) {
        for (var y = 1; y <= x; y++) {
            intArrJ0 = parseInt(arr[y - 1].split(".")[0]);
            intArrJ = parseInt(arr[y].split(".")[0]);

            if ((intArrJ0 > intArrJ)) {
                var tmp = arr[y - 1];
                arr[y - 1] = arr[y];
                arr[y] = tmp;
            }
        }
    }
}
  
    return arr;
}



var arr = ['1.1', '1.9', '1.11', '1.8', '1.12', '2.1', '2.11', '3.1'];
console.log(arr.sort());
console.log("=====>");
console.log(customSort(arr));
Rezultatul:

Input:
["1.1", "1.11", "1.12", "1.8", "1.9", "2.1", "2.11", "3.1"]
Output:
["1.1", "1.8", "1.9", "1.11", "1.12", "2.1", "2.11", "3.1"]
Pentru întrebări, vă stăm la dispoziție.

Autor thread: stefanciprian, Echipa Specialişti IT

Mulțumesc
Moderator și Specialist IT
Scrie răspuns