itsource

속성 값을 기준으로 개체 배열 정렬

mycopycode 2023. 1. 19. 07:08
반응형

속성 값을 기준으로 개체 배열 정렬

AJAX를 사용하여 다음 개체를 가져와서 배열에 저장했습니다.

var homes = [
    {
        "h_id": "3",
        "city": "Dallas",
        "state": "TX",
        "zip": "75201",
        "price": "162500"
    }, {
        "h_id": "4",
        "city": "Bevery Hills",
        "state": "CA",
        "zip": "90210",
        "price": "319250"
    }, {
        "h_id": "5",
        "city": "New York",
        "state": "NY",
        "zip": "00010",
        "price": "962500"
    }
];

어떻게 요?price JavaScript만 사용하여 오름차순 내림차순으로 속성을 지정합니다.

가격별로 오름차순으로 주택 정렬:

homes.sort(function(a, b) {
    return parseFloat(a.price) - parseFloat(b.price);
});

또는 ES6 버전 이후:

homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));

일부 설명서는 여기에서 찾을 수 있습니다.

내림차순의 경우 다음을 사용할 수 있습니다.

homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));

여기 보다 유연한 버전이 있습니다. 재사용 가능한 정렬 함수를 만들고 모든 필드를 기준으로 정렬할 수 있습니다.

const sort_by = (field, reverse, primer) => {

  const key = primer ?
    function(x) {
      return primer(x[field])
    } :
    function(x) {
      return x[field]
    };

  reverse = !reverse ? 1 : -1;

  return function(a, b) {
    return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
  }
}


//Now you can sort by any field at will...

const homes=[{h_id:"3",city:"Dallas",state:"TX",zip:"75201",price:"162500"},{h_id:"4",city:"Bevery Hills",state:"CA",zip:"90210",price:"319250"},{h_id:"5",city:"New York",state:"NY",zip:"00010",price:"962500"}];

// Sort by price high to low
console.log(homes.sort(sort_by('price', true, parseInt)));

// Sort by city, case-insensitive, A-Z
console.log(homes.sort(sort_by('city', false, (a) =>  a.toUpperCase()
)));

정렬하려면 두 개의 인수를 사용하여 비교 함수를 만들어야 합니다.그런 다음 다음과 같이 비교기 함수를 사용하여 정렬 함수를 호출합니다.

// a and b are object elements of your array
function mycomparator(a,b) {
  return parseInt(a.price, 10) - parseInt(b.price, 10);
}
homes.sort(mycomparator);

오름차순으로 정렬하려면 마이너스 기호 양쪽에 있는 식을 바꿉니다.

누군가 필요할 때를 대비해서 현악기 분류를 하고,

const dataArr = {

  "hello": [{
    "id": 114,
    "keyword": "zzzzzz",
    "region": "Sri Lanka",
    "supportGroup": "administrators",
    "category": "Category2"
  }, {
    "id": 115,
    "keyword": "aaaaa",
    "region": "Japan",
    "supportGroup": "developers",
    "category": "Category2"
  }]

};
const sortArray = dataArr['hello'];

console.log(sortArray.sort((a, b) => {
  if (a.region < b.region)
    return -1;
  if (a.region > b.region)
    return 1;
  return 0;
}));

ES6 준거 브라우저를 사용하는 경우 다음을 사용할 수 있습니다.

오름차순과 내림차순의 차이는 비교함수에 의해 반환되는 값의 부호입니다.

var ascending = homes.sort((a, b) => Number(a.price) - Number(b.price));
var descending = homes.sort((a, b) => Number(b.price) - Number(a.price));

다음은 작동 코드 스니펫입니다.

var homes = [{
  "h_id": "3",
  "city": "Dallas",
  "state": "TX",
  "zip": "75201",
  "price": "162500"
}, {
  "h_id": "4",
  "city": "Bevery Hills",
  "state": "CA",
  "zip": "90210",
  "price": "319250"
}, {
  "h_id": "5",
  "city": "New York",
  "state": "NY",
  "zip": "00010",
  "price": "962500"
}];

homes.sort((a, b) => Number(a.price) - Number(b.price));
console.log("ascending", homes);

homes.sort((a, b) => Number(b.price) - Number(a.price));
console.log("descending", homes);

Javascript로 정렬하고 싶은 거죠?당신이 원하는 것은 기능이다.이 경우 비교 함수를 작성하여 다음 주소로 전달해야 합니다.sort(), 하다, 하다, 하다' 이런

function comparator(a, b) {
    return parseInt(a["price"], 10) - parseInt(b["price"], 10);
}

var json = { "homes": [ /* your previous data */ ] };
console.log(json["homes"].sort(comparator));

비교기는 배열 내에서 중첩된 각 해시를 하나씩 가져와서 "가격" 필드를 확인하여 더 높은 해시를 결정합니다.

GitHub: Array sortBy - 최적의 구현sortBySchwartzian 변환을 사용하는 방법

다만, 현시점에서는, Gist:sortBy-old.js 라고 하는 어프로치를 시험합니다.
오브젝트를 특정 속성별로 정렬할 수 있는 어레이를 정렬하는 메서드를 만듭니다.

정렬 기능 생성

var sortBy = (function () {
  var toString = Object.prototype.toString,
      // default parser function
      parse = function (x) { return x; },
      // gets the item to be sorted
      getItem = function (x) {
        var isObject = x != null && typeof x === "object";
        var isProp = isObject && this.prop in x;
        return this.parser(isProp ? x[this.prop] : x);
      };
      
  /**
   * Sorts an array of elements.
   *
   * @param  {Array} array: the collection to sort
   * @param  {Object} cfg: the configuration options
   * @property {String}   cfg.prop: property name (if it is an Array of objects)
   * @property {Boolean}  cfg.desc: determines whether the sort is descending
   * @property {Function} cfg.parser: function to parse the items to expected type
   * @return {Array}
   */
  return function sortby (array, cfg) {
    if (!(array instanceof Array && array.length)) return [];
    if (toString.call(cfg) !== "[object Object]") cfg = {};
    if (typeof cfg.parser !== "function") cfg.parser = parse;
    cfg.desc = !!cfg.desc ? -1 : 1;
    return array.sort(function (a, b) {
      a = getItem.call(cfg, a);
      b = getItem.call(cfg, b);
      return cfg.desc * (a < b ? -1 : +(a > b));
    });
  };
  
}());

정렬되지 않은 데이터 설정

var data = [
  {date: "2011-11-14T16:30:43Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90,  tip: 0,   type: "Tab"},
  {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
  {date: "2011-11-14T16:53:41Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T16:48:46Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0,   type: "cash"},
  {date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"},
  {date: "2011-11-14T16:58:03Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T17:07:21Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0,   type: "Cash"}
];

사용법

Arrange the array, by 배열을 정렬합니다."date" as ~하듯이String

// sort by @date (ascending)
sortBy(data, { prop: "date" });

// expected: first element
// { date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab" }

// expected: last element
// { date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"}

케이스 민감하게 무시하려면 소 문 분 하 우 는 if you,, sensitive the경 case는 want않 to ignore구대)를 무시합니다.parser전화:콜백:

// sort by @type (ascending) IGNORING case-sensitive
sortBy(data, {
    prop: "type",
    parser: (t) => t.toUpperCase()
});

// expected: first element
// { date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "Cash" }

// expected: last element
// { date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa" }

If you want to convert the 변환하는 경우"date" field as 로서 활약하다.Date 삭제:

// sort by @date (descending) AS Date object
sortBy(data, {
    prop: "date",
    desc: true,
    parser: (d) => new Date(d)
});

// expected: first element
// { date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"}

// expected: last element
// { date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab" }

여기에서는, 다음의 코드로 플레이 할 수 있습니다.jsbin.com/lesebi

@Ozesh의 피드백 덕분에 가짜 가치가 있는 부동산에 관한 문제가 해결되었습니다.

lodash.sortBy 를 사용합니다(commonjs 를 사용하는 순서는, html 의 선두에 cdn스크립트 include-tag 를 붙이기만 하면 됩니다).

var sortBy = require('lodash.sortby');
// or
sortBy = require('lodash').sortBy;

내림차순

var descendingOrder = sortBy( homes, 'price' ).reverse();

오름차순

var ascendingOrder = sortBy( homes, 'price' );

나는 파티에 조금 늦었지만 아래는 분류에 대한 나의 논리다.

function getSortedData(data, prop, isAsc) {
    return data.sort((a, b) => {
        return (a[prop] < b[prop] ? -1 : 1) * (isAsc ? 1 : -1)
    });
}

문자열 비교에 string1.locale Compare(string2)를 사용할 수 있습니다.

this.myArray.sort((a,b) => { 
    return a.stringProp.localeCompare(b.stringProp);
});

:localCompare대소문자를 구분하지 않음

이것은 단순한 한 줄 값 of() 정렬 함수를 통해 달성할 수 있습니다.데모를 보려면 아래의 코드 스니펫을 실행하십시오.

var homes = [
    {
        "h_id": "3",
        "city": "Dallas",
        "state": "TX",
        "zip": "75201",
        "price": "162500"
    }, {
        "h_id": "4",
        "city": "Bevery Hills",
        "state": "CA",
        "zip": "90210",
        "price": "319250"
    }, {
        "h_id": "5",
        "city": "New York",
        "state": "NY",
        "zip": "00010",
        "price": "962500"
    }
];

console.log("To sort descending/highest first, use operator '<'");

homes.sort(function(a,b) { return a.price.valueOf() < b.price.valueOf();});

console.log(homes);

console.log("To sort ascending/lowest first, use operator '>'");

homes.sort(function(a,b) { return a.price.valueOf() > b.price.valueOf();});

console.log(homes);

가격 내림차순:

homes.sort((x,y) => {return y.price - x.price})

가격 오름차순:

homes.sort((x,y) => {return x.price - y.price})

OP가 일련의 숫자를 정렬하고 싶어한다는 것을 알고 있지만, 이 질문은 문자열에 관한 유사한 질문에 대한 답변으로 표시되어 있습니다.그 때문에, 상기의 답변에서는, 대소문자가 중요한 텍스트의 배열을 분류하는 것은 고려하지 않습니다.대부분의 응답은 문자열 값을 대문자/소문자로 변환한 다음 어떤 방식으로든 정렬합니다.내가 준수하는 요건은 다음과 같습니다.

  • 알파벳 순으로 정렬
  • 같은 단어의 대문자 값은 소문자 값보다 앞에 와야 합니다.
  • 동일한 문자(A/a, B/b) 값을 함께 그룹화해야 합니다.

가 하는 것은 ★★★★★★★★★★★★★★★★★★★★★★★★★★★.[ A, a, B, b, C, c ] 위의 은 반환됩니다.A, B, C, a, b, c사실 제가 원하던 것보다 오래 머리를 긁적거렸습니다(그래서 한 분이라도 도움이 되길 바라며 이 글을 올렸습니다).의 이름을 언급하고 있는 localeCompare표기된 답변의 코멘트에 기능이 기재되어 있는 것을, 검색중에 우연히 기능을 발견하게 된 후가 되어 버렸습니다.String.protype.localeCompare() 문서를 읽고 다음과 같이 생각할 수 있었습니다.

var values = [ "Delta", "charlie", "delta", "Charlie", "Bravo", "alpha", "Alpha", "bravo" ];
var sorted = values.sort((a, b) => a.localeCompare(b, undefined, { caseFirst: "upper" }));
// Result: [ "Alpha", "alpha", "Bravo", "bravo", "Charlie", "charlie", "Delta", "delta" ]

그러면 함수는 소문자 값보다 대문자 값을 먼저 정렬하도록 지시합니다.의 두 localeCompare인데, 로케일로 로케일이 정의됩니다.undefined이치노

이것은 오브젝트 배열 정렬에도 동일하게 동작합니다.

var values = [
    { id: 6, title: "Delta" },
    { id: 2, title: "charlie" },
    { id: 3, title: "delta" },
    { id: 1, title: "Charlie" },
    { id: 8, title: "Bravo" },
    { id: 5, title: "alpha" },
    { id: 4, title: "Alpha" },
    { id: 7, title: "bravo" }
];
var sorted = values
    .sort((a, b) => a.title.localeCompare(b.title, undefined, { caseFirst: "upper" }));

여기 위의 모든 답변이 정리되어 있습니다.

바이올린 검증: http://jsfiddle.net/bobberino/4qqk3/

var sortOn = function (arr, prop, reverse, numeric) {

    // Ensure there's a property
    if (!prop || !arr) {
        return arr
    }

    // Set up sort function
    var sort_by = function (field, rev, primer) {

        // Return the required a,b function
        return function (a, b) {

            // Reset a, b to the field
            a = primer(a[field]), b = primer(b[field]);

            // Do actual sorting, reverse as needed
            return ((a < b) ? -1 : ((a > b) ? 1 : 0)) * (rev ? -1 : 1);
        }

    }

    // Distinguish between numeric and string to prevent 100's from coming before smaller
    // e.g.
    // 1
    // 20
    // 3
    // 4000
    // 50

    if (numeric) {

        // Do sort "in place" with sort_by function
        arr.sort(sort_by(prop, reverse, function (a) {

            // - Force value to a string.
            // - Replace any non numeric characters.
            // - Parse as float to allow 0.02 values.
            return parseFloat(String(a).replace(/[^0-9.-]+/g, ''));

        }));
    } else {

        // Do sort "in place" with sort_by function
        arr.sort(sort_by(prop, reverse, function (a) {

            // - Force value to string.
            return String(a).toUpperCase();

        }));
    }


}

배열을 정렬하려면 비교 함수를 정의해야 합니다.이 기능은 원하는 정렬 패턴 또는 순서(예: 오름차순 또는 내림차순)에서 항상 다릅니다.

배열을 오름차순 또는 내림차순으로 정렬하고 개체 또는 문자열 또는 숫자 값을 포함하는 함수를 만듭니다.

function sorterAscending(a,b) {
    return a-b;
}

function sorterDescending(a,b) {
    return b-a;
}

function sorterPriceAsc(a,b) {
    return parseInt(a['price']) - parseInt(b['price']);
}

function sorterPriceDes(a,b) {
    return parseInt(b['price']) - parseInt(b['price']);
}

정렬 번호(알파벳 및 오름차순):

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

정렬 번호(알파벳 및 내림차순):

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();

정렬 번호(숫자 및 오름차순):

var points = [40,100,1,5,25,10];
points.sort(sorterAscending());

정렬 번호(숫자 및 내림차순):

var points = [40,100,1,5,25,10];
points.sort(sorterDescending());

위와 같이 원하는 키를 가진 어레이와 함께 sorterPriceAsc 및 sorterPriceDes 메서드를 사용합니다.

homes.sort(sorterPriceAsc()) or homes.sort(sorterPriceDes())

JavaScript 를 할 수 .sort" " " 백수가가수가가 。

function compareASC(homeA, homeB)
{
    return parseFloat(homeA.price) - parseFloat(homeB.price);
}

function compareDESC(homeA, homeB)
{
    return parseFloat(homeB.price) - parseFloat(homeA.price);
}

// Sort ASC
homes.sort(compareASC);

// Sort DESC
homes.sort(compareDESC);

또, 일종의 평가나 복수의 필드 분류에 대해서도 작업을 실시했습니다.

arr = [
    {type:'C', note:834},
    {type:'D', note:732},
    {type:'D', note:008},
    {type:'F', note:474},
    {type:'P', note:283},
    {type:'P', note:165},
    {type:'X', note:173},
    {type:'Z', note:239},
];

arr.sort(function(a,b){        
    var _a = ((a.type==='C')?'0':(a.type==='P')?'1':'2');
    _a += (a.type.localeCompare(b.type)===-1)?'0':'1';
    _a += (a.note>b.note)?'1':'0';
    var _b = ((b.type==='C')?'0':(b.type==='P')?'1':'2');
    _b += (b.type.localeCompare(a.type)===-1)?'0':'1';
    _b += (b.note>a.note)?'1':'0';
    return parseInt(_a) - parseInt(_b);
});

결과

[
    {"type":"C","note":834},
    {"type":"P","note":165},
    {"type":"P","note":283},
    {"type":"D","note":8},
    {"type":"D","note":732},
    {"type":"F","note":474},
    {"type":"X","note":173},
    {"type":"Z","note":239}
]

하나의 어레이를 정렬하기에는 다소 무리가 있지만, 이 프로토타입 함수는 자바스크립트 어레이를 네스트된 키를 포함한 오름차순 또는 내림차순으로 정렬할 수 있습니다.dot구문을 사용합니다.

(function(){
    var keyPaths = [];

    var saveKeyPath = function(path) {
        keyPaths.push({
            sign: (path[0] === '+' || path[0] === '-')? parseInt(path.shift()+1) : 1,
            path: path
        });
    };

    var valueOf = function(object, path) {
        var ptr = object;
        for (var i=0,l=path.length; i<l; i++) ptr = ptr[path[i]];
        return ptr;
    };

    var comparer = function(a, b) {
        for (var i = 0, l = keyPaths.length; i < l; i++) {
            aVal = valueOf(a, keyPaths[i].path);
            bVal = valueOf(b, keyPaths[i].path);
            if (aVal > bVal) return keyPaths[i].sign;
            if (aVal < bVal) return -keyPaths[i].sign;
        }
        return 0;
    };

    Array.prototype.sortBy = function() {
        keyPaths = [];
        for (var i=0,l=arguments.length; i<l; i++) {
            switch (typeof(arguments[i])) {
                case "object": saveKeyPath(arguments[i]); break;
                case "string": saveKeyPath(arguments[i].match(/[+-]|[^.]+/g)); break;
            }
        }
        return this.sort(comparer);
    };    
})();

사용방법:

var data = [
    { name: { first: 'Josh', last: 'Jones' }, age: 30 },
    { name: { first: 'Carlos', last: 'Jacques' }, age: 19 },
    { name: { first: 'Carlos', last: 'Dante' }, age: 23 },
    { name: { first: 'Tim', last: 'Marley' }, age: 9 },
    { name: { first: 'Courtney', last: 'Smith' }, age: 27 },
    { name: { first: 'Bob', last: 'Smith' }, age: 30 }
]

data.sortBy('age'); // "Tim Marley(9)", "Carlos Jacques(19)", "Carlos Dante(23)", "Courtney Smith(27)", "Josh Jones(30)", "Bob Smith(30)"

dot-syntax 또는 array-syntax를 사용하여 중첩된 속성을 기준으로 정렬:

data.sortBy('name.first'); // "Bob Smith(30)", "Carlos Dante(23)", "Carlos Jacques(19)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"
data.sortBy(['name', 'first']); // "Bob Smith(30)", "Carlos Dante(23)", "Carlos Jacques(19)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"

여러 키를 기준으로 정렬:

data.sortBy('name.first', 'age'); // "Bob Smith(30)", "Carlos Jacques(19)", "Carlos Dante(23)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"
data.sortBy('name.first', '-age'); // "Bob Smith(30)", "Carlos Dante(23)", "Carlos Jacques(19)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"

문의는 https://github.com/eneko/Array.sortBy 에서 할 수 있습니다.

ECMAScript 6 StoBor의 답변은 보다 간결하게 할 수 있습니다.

homes.sort((a, b) => a.price - b.price)

요소 값의 일반 배열의 경우:

function sortArrayOfElements(arrayToSort) {
    function compareElements(a, b) {
        if (a < b)
            return -1;
        if (a > b)
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareElements);
}

e.g. 1:
var array1 = [1,2,545,676,64,2,24]
output : [1, 2, 2, 24, 64, 545, 676]

var array2 = ["v","a",545,676,64,2,"24"]
output: ["a", "v", 2, "24", 64, 545, 676]

객체 배열의 경우:

function sortArrayOfObjects(arrayToSort, key) {
    function compareObjects(a, b) {
        if (a[key] < b[key])
            return -1;
        if (a[key] > b[key])
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareObjects);
}

e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]

output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]

Underscore.js를 사용하는 경우 sortBy:

// price is of an integer type
_.sortBy(homes, "price"); 

// price is of a string type
_.sortBy(homes, function(home) {return parseInt(home.price);}); 

다음은 "JavaScript:좋은 부분"을 참조하십시오.

주의: 이 버전의by안정적입니다.첫 번째 정렬 순서를 유지하면서 다음 체인 정렬을 수행합니다.

가가 i i i i i를 했습니다.isAscending파라미터를 지정합니다., 환 it it it it it it로 변환했습니다.ES6저자가 추천한 대로 좋은 부분과 표준적인 부분을 '고정'할 수 있습니다.

여러 속성을 기준으로 오름차순 및 내림차순 및 체인 정렬을 수행할 수 있습니다.

const by = function (name, minor, isAscending=true) {
    const reverseMutliplier = isAscending ? 1 : -1;
    return function (o, p) {
        let a, b;
        let result;
        if (o && p && typeof o === "object" && typeof p === "object") {
            a = o[name];
            b = p[name];
            if (a === b) {
                return typeof minor === 'function' ? minor(o, p) : 0;
            }
            if (typeof a === typeof b) {
                result = a < b ? -1 : 1;
            } else {
                result = typeof a < typeof b ? -1 : 1;
            }
            return result * reverseMutliplier;
        } else {
            throw {
                name: "Error",
                message: "Expected an object when sorting by " + name
            };
        }
    };
};

let s = [
    {first: 'Joe',   last: 'Besser'},
    {first: 'Moe',   last: 'Howard'},
    {first: 'Joe',   last: 'DeRita'},
    {first: 'Shemp', last: 'Howard'},
    {first: 'Larry', last: 'Fine'},
    {first: 'Curly', last: 'Howard'}
];

// Sort by: first ascending, last ascending
s.sort(by("first", by("last")));    
console.log("Sort by: first ascending, last ascending: ", s);     // "[
//     {"first":"Curly","last":"Howard"},
//     {"first":"Joe","last":"Besser"},     <======
//     {"first":"Joe","last":"DeRita"},     <======
//     {"first":"Larry","last":"Fine"},
//     {"first":"Moe","last":"Howard"},
//     {"first":"Shemp","last":"Howard"}
// ]

// Sort by: first ascending, last descending
s.sort(by("first", by("last", 0, false)));  
console.log("sort by: first ascending, last descending: ", s);    // "[
//     {"first":"Curly","last":"Howard"},
//     {"first":"Joe","last":"DeRita"},     <========
//     {"first":"Joe","last":"Besser"},     <========
//     {"first":"Larry","last":"Fine"},
//     {"first":"Moe","last":"Howard"},
//     {"first":"Shemp","last":"Howard"}
// ]

함수를 만들고 아래 코드를 사용하여 입력을 기준으로 정렬합니다.

var homes = [{

    "h_id": "3",
    "city": "Dallas",
    "state": "TX",
    "zip": "75201",
    "price": "162500"

 }, {

    "h_id": "4",
    "city": "Bevery Hills",
    "state": "CA",
    "zip": "90210",
    "price": "319250"

 }, {

    "h_id": "5",
    "city": "New York",
    "state": "NY",
    "zip": "00010",
    "price": "962500"

 }];

 function sortList(list,order){
     if(order=="ASC"){
        return list.sort((a,b)=>{
            return parseFloat(a.price) - parseFloat(b.price);
        })
     }
     else{
        return list.sort((a,b)=>{
            return parseFloat(b.price) - parseFloat(a.price);
        });
     }
 }

 sortList(homes,'DESC');
 console.log(homes);

LINQ와 같은 솔루션:

Array.prototype.orderBy = function (selector, desc = false) {
    return [...this].sort((a, b) => {
        a = selector(a);
        b = selector(b);

        if (a == b) return 0;
        return (desc ? a > b : a < b) ? -1 : 1;
    });
}

장점:

  • 속성에 대한 자동 완성
  • 어레이 프로토타입 확장
  • 어레이는 변경되지 않습니다.
  • 메서드 체인에서 사용하기 쉽다

사용방법:

Array.prototype.orderBy = function(selector, desc = false) {
  return [...this].sort((a, b) => {
    a = selector(a);
    b = selector(b);

    if (a == b) return 0;
    return (desc ? a > b : a < b) ? -1 : 1;
  });
};

var homes = [{
  "h_id": "3",
  "city": "Dallas",
  "state": "TX",
  "zip": "75201",
  "price": "162500"
}, {
  "h_id": "4",
  "city": "Bevery Hills",
  "state": "CA",
  "zip": "90210",
  "price": "319250"
}, {
  "h_id": "5",
  "city": "New York",
  "state": "NY",
  "zip": "00010",
  "price": "962500"
}];

let sorted_homes = homes.orderBy(h => parseFloat(h.price));
console.log("sorted by price", sorted_homes);

let sorted_homes_desc = homes.orderBy(h => h.city, true);
console.log("sorted by City descending", sorted_homes_desc);

이 기능을 사용하다

const r_sort = (a, b, field, asc) => {
    let reverse = asc ? 1 : -1;
    if (a[field] > b[field]) {
        return 1 * reverse;
    }
    else if (b[field] > a[field]) {
        return -1 * reverse;
    }
    else {
        return 0;
    } }

//실행:

homes = homes.sort((a,b) => r_sort(a,b,price,true)) // true for ascending and false for descending

하다.arrprop like ["a","b","c"] 다음 두 매개 변수를 합니다.arrsource정렬하고 싶은 실제 소스입니다.

function SortArrayobject(arrprop,arrsource){
arrprop.forEach(function(i){
arrsource.sort(function(a,b){
return ((a[i] < b[i]) ? -1 : ((a[i] > b[i]) ? 1 : 0));
});
});
return arrsource;
}

두 가지 기능이 필요합니다.

function desc(a, b) {
 return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

function asc(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

다음으로 임의의 오브젝트속성에 적용할 수 있습니다.

 data.sort((a, b) => desc(parseFloat(a.price), parseFloat(b.price)));

let data = [
    {label: "one", value:10},
    {label: "two", value:5},
    {label: "three", value:1},
];

// sort functions
function desc(a, b) {
 return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

function asc(a, b) {
 return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// DESC
data.sort((a, b) => desc(a.value, b.value));

document.body.insertAdjacentHTML(
 'beforeend', 
 '<strong>DESCending sorted</strong><pre>' + JSON.stringify(data) +'</pre>'
);

// ASC
data.sort((a, b) => asc(a.value, b.value));

document.body.insertAdjacentHTML(
 'beforeend', 
 '<strong>ASCending sorted</strong><pre>' + JSON.stringify(data) +'</pre>'
);

사용하실 수 있도록 유니버설 기능을 작성했습니다.

/**
 * Sorts an object into an order
 *
 * @require jQuery
 *
 * @param object Our JSON object to sort
 * @param type Only alphabetical at the moment
 * @param identifier The array or object key to sort by
 * @param order Ascending or Descending
 *
 * @returns Array
 */
function sortItems(object, type, identifier, order){

    var returnedArray = [];
    var emptiesArray = []; // An array for all of our empty cans

    // Convert the given object to an array
    $.each(object, function(key, object){

        // Store all of our empty cans in their own array
        // Store all other objects in our returned array
        object[identifier] == null ? emptiesArray.push(object) : returnedArray.push(object);

    });

    // Sort the array based on the type given
    switch(type){

        case 'alphabetical':

            returnedArray.sort(function(a, b){

                return(a[identifier] == b[identifier]) ? 0 : (

                    // Sort ascending or descending based on order given
                    order == 'asc' ? a[identifier] > b[identifier] : a[identifier] < b[identifier]

                ) ? 1 : -1;

            });

            break;

        default:

    }

    // Return our sorted array along with the empties at the bottom depending on sort order
    return order == 'asc' ? returnedArray.concat(emptiesArray) : emptiesArray.concat(returnedArray);

}
homes.sort(function(a, b){
  var nameA=a.prices.toLowerCase(), nameB=b.prices.toLowerCase()
  if (nameA < nameB) //sort string ascending
    return -1 
  if (nameA > nameB)
    return 1
  return 0 //default return value (no sorting)
})

안녕하세요, 이 기사를 읽고 제 요구에 맞는 sort Comparator를 만들었습니다.여러 json 속성을 비교할 수 있는 기능을 갖추고 있습니다.여러분들과 공유하겠습니다.

이 솔루션에서는 문자열만 오름차순으로 비교하지만 각 속성(역순서, 기타 데이터 유형, 로케일 사용, 캐스팅 등)에 대해 솔루션을 쉽게 확장할 수 있습니다.

var homes = [{

    "h_id": "3",
    "city": "Dallas",
    "state": "TX",
    "zip": "75201",
    "price": "162500"

}, {

    "h_id": "4",
    "city": "Bevery Hills",
    "state": "CA",
    "zip": "90210",
    "price": "319250"

}, {

    "h_id": "5",
    "city": "New York",
    "state": "NY",
    "zip": "00010",
    "price": "962500"

}];

// comp = array of attributes to sort
// comp = ['attr1', 'attr2', 'attr3', ...]
function sortComparator(a, b, comp) {
    // Compare the values of the first attribute
    if (a[comp[0]] === b[comp[0]]) {
        // if EQ proceed with the next attributes
        if (comp.length > 1) {
            return sortComparator(a, b, comp.slice(1));
        } else {
            // if no more attributes then return EQ
            return 0;
        }
    } else {
        // return less or great
        return (a[comp[0]] < b[comp[0]] ? -1 : 1)
    }
}

// Sort array homes
homes.sort(function(a, b) {
    return sortComparator(a, b, ['state', 'city', 'zip']);
});

// display the array
homes.forEach(function(home) {
    console.log(home.h_id, home.city, home.state, home.zip, home.price);
});

그 결과

$ node sort
4 Bevery Hills CA 90210 319250
5 New York NY 00010 962500
3 Dallas TX 75201 162500

그리고 다른 종류

homes.sort(function(a, b) {
    return sortComparator(a, b, ['city', 'zip']);
});

결과적으로

$ node sort
4 Bevery Hills CA 90210 319250
3 Dallas TX 75201 162500
5 New York NY 00010 962500

언급URL : https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values

반응형