“Sortir array berdasarkan dua properti” Kode Jawaban

JavaScript Sort Array dengan beberapa properti

var sort_by;

(function() {
    // utility functions
    var default_cmp = function(a, b) {
            if (a == b) return 0;
            return a < b ? -1 : 1;
        },
        getCmpFunc = function(primer, reverse) {
            var dfc = default_cmp, // closer in scope
                cmp = default_cmp;
            if (primer) {
                cmp = function(a, b) {
                    return dfc(primer(a), primer(b));
                };
            }
            if (reverse) {
                return function(a, b) {
                    return -1 * cmp(a, b);
                };
            }
            return cmp;
        };

    // actual implementation
    sort_by = function() {
        var fields = [],
            n_fields = arguments.length,
            field, name, reverse, cmp;

        // preprocess sorting options
        for (var i = 0; i < n_fields; i++) {
            field = arguments[i];
            if (typeof field === 'string') {
                name = field;
                cmp = default_cmp;
            }
            else {
                name = field.name;
                cmp = getCmpFunc(field.primer, field.reverse);
            }
            fields.push({
                name: name,
                cmp: cmp
            });
        }

        // final comparison function
        return function(A, B) {
            var a, b, name, result;
            for (var i = 0; i < n_fields; i++) {
                result = 0;
                field = fields[i];
                name = field.name;

                result = field.cmp(A[name], B[name]);
                if (result !== 0) break;
            }
            return result;
        }
    }
}());
Cruel Chinchilla

Sortir array berdasarkan dua properti

console.log(fruits.sort((a, b)=> {
  if (a.colA === b.colA){
    return a.colB < b.colB ? -1 : 1
  } else {
    return a.colA < b.colA ? -1 : 1
  }
}))

/*
> [{colA: "apple", colB: "granny smith"},
  {colA: "apple", colB: "red delicious"},
  {colA: "orange", colB: "blood"},
  {colA: "orange", colB: "clementine"},
  {colA: "orange", colB: "navel"},
  {colA": "pear", colB: "green anjou"},
  {colA: "pear", colB: "red anjou"}]
  */
Worried Wolverine

Jawaban yang mirip dengan “Sortir array berdasarkan dua properti”

Pertanyaan yang mirip dengan “Sortir array berdasarkan dua properti”

Lebih banyak jawaban terkait untuk “Sortir array berdasarkan dua properti” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya