etc./StackOverFlow

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

청렴결백한 만능 재주꾼 2022. 2. 17. 12:25
반응형

질문자 :Community Wiki


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" } ];

JavaScript만 사용하여 price 속성을 기준 으로 오름차순 또는 내림차순 으로 개체를 정렬하는 함수를 만들려면 어떻게 해야 합니까?



가격에 따라 오름차순으로 주택 정렬:

 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));

Stobor

다음은 재사용 가능한 정렬 기능을 만들고 모든 필드를 기준으로 정렬할 수 있는 보다 유연한 버전입니다.

 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, AZ console.log(homes.sort(sort_by('city', false, (a) => a.toUpperCase() )));


Triptych

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

 // 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);

오름차순으로 정렬하려면 빼기 기호의 양쪽에 있는 표현식을 전환하십시오.


Ricardo Marimon

누군가가 그것을 필요로하는 경우를 대비하여 문자열 정렬을 위해,

 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; }));


Community Wiki

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);


Community Wiki

Javascript로 정렬하고 싶습니까? 원하는 것은 sort() 함수 입니다. 이 경우 비교기 함수를 작성하고 이를 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));

비교기는 배열 내부의 각 중첩 해시 중 하나를 취하고 "가격" 필드를 확인하여 어느 것이 더 높은지 결정합니다.


Tim Gilbert

나는 GitHub를 추천합니다 : Array sortBy - Schwartzian 변환 을 사용하는 sortBy 메소드의 가장 좋은 구현

그러나 지금은 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"} ];

그것을 사용

String"date" 별로 배열을 정렬합니다.

 // 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"}

대소문자를 구분하지 않으려면 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" }

"date" 필드를 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의 피드백 덕분에 값이 잘못된 속성과 관련된 문제가 수정되었습니다.


Community Wiki

lodash.sortBy 사용( commonjs를 사용하는 지침, cdn에 대한 스크립트 include-tag를 HTML 상단에 넣을 수도 있음)

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

내림차순

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

오름차순

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

Community Wiki

나는 파티에 조금 늦었지만 아래는 정렬에 대한 내 논리입니다.

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

Community Wiki

이것은 간단한 한 줄 valueof() 정렬 함수를 통해 달성할 수 있습니다. 데모를 보려면 아래 코드 스니펫을 실행하세요.

 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);


Community Wiki

OP가 숫자 배열을 정렬하려고 한다는 것을 알고 있지만 이 질문은 문자열과 관련된 유사한 질문에 대한 답변으로 표시되었습니다. 그 사실에 대해 위의 답변은 대소문자가 중요한 텍스트 배열을 정렬하는 것을 고려하지 않습니다. 대부분의 답변은 문자열 값을 가져와 대문자/소문자로 변환한 다음 어떤 방식으로든 정렬합니다. 내가 준수하는 요구 사항은 간단합니다.

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

내가 기대하는 것은 [ A, a, B, b, C, c ] 이지만 위의 답변은 A, B, C, a, b, c 반환합니다. 나는 실제로 내가 원했던 것보다 더 오랫동안 이것에 대해 머리를 긁적였습니다(이것이 내가 적어도 한 명의 다른 사람에게 도움이 되기를 바라는 마음에서 이것을 게시하는 이유입니다). 두 명의 사용자 localeCompare 기능을 언급했지만 검색하는 동안 해당 기능을 우연히 발견할 때까지 그 기능을 보지 못했습니다. String.prototype.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" }));

Community Wiki

가격 내림차순:

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

가격 오름차순:

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

Community Wiki

다음은 위의 모든 답변의 절정입니다.

바이올린 유효성 검사: 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 // eg // 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(); })); } }

Community Wiki

문자열 비교를 위해 string1.localeCompare(string2)를 사용할 수 있습니다.

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

localCompare 는 대소문자 구분합니다.


Community Wiki

콜백 함수와 함께 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);

John G

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

배열을 오름차순 또는 내림차순으로 정렬하고 개체, 문자열 또는 숫자 값을 포함하는 몇 가지 함수를 만들어 보겠습니다.

 function sorterAscending(a,b) { return ab; } function sorterDescending(a,b) { return ba; } 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())

Community Wiki

나는 또한 일종의 평가 및 여러 필드 정렬로 작업했습니다.

 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} ]

Community Wiki

단일 배열을 정렬하기에는 다소 무리가 있지만 이 프로토타입 기능을 사용하면 dot 구문을 사용 하여 중첩 키를 포함하여 모든 키를 기준으로 Javascript 배열을 오름차순 또는 내림차순으로 정렬할 수 있습니다.

 (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)"

점 구문 또는 배열 구문을 사용하여 중첩 속성을 기준으로 정렬:

 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


Community Wiki

ECMAScript 6 StoBor를 사용하면 훨씬 더 간결하게 답변할 수 있습니다.

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

Community Wiki

요소 값의 일반 배열에만 해당:

 function sortArrayOfElements(arrayToSort) { function compareElements(a, b) { if (a < b) return -1; if (a > b) return 1; return 0; } return arrayToSort.sort(compareElements); } eg 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); } eg 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}]

Community Wiki

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);});

Community Wiki

다음은 "JavaScript: Good Parts" 책의 우아한 구현을 약간 수정한 버전입니다.

참고 : 이 버전의 by안정적 입니다. 다음 연결 정렬을 수행하는 동안 첫 번째 정렬의 순서를 유지합니다.

isAscending 매개변수를 추가했습니다. 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"} // ]


Community Wiki

아래 코드를 사용하여 입력을 기반으로 함수를 만들고 정렬하십시오.

 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);

Community Wiki

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);


Community Wiki

다중 배열 개체 필드에 대한 정렬의 경우. ["a","b","c"] 와 같은 arrprop 배열에 필드 이름을 입력한 다음 정렬하려는 두 번째 매개변수 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; }

Community Wiki

두 가지 기능이 필요합니다

 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>' );


Community Wiki

나는 최근에 이것을 사용하고 싶다면 이것을 관리하는 범용 함수를 작성했습니다.

 /** * 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); }

Community Wiki

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) })

Community Wiki

안녕하세요. 이 기사를 읽은 후 필요에 따라 하나 이상의 json 속성을 비교하는 기능을 갖춘 sortComparator를 만들었습니다. 이 기능을 여러분과 공유하고 싶습니다.

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

 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

Community Wiki

간단한 코드:

 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 sortByPrice = homes.sort(function (a, b) { return parseFloat(b.price) - parseFloat(a.price); }); for (var i=0; i<sortByPrice.length; i++) { document.write(sortByPrice[i].h_id+' '+sortByPrice[i].city+' ' +sortByPrice[i].state+' ' +sortByPrice[i].zip+' '+sortByPrice[i].price); document.write("<br>"); }


Community Wiki

출처 : http:www.stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values

반응형