Sorting an array of JavaScript objects by property
我使用Ajax读取了以下对象,并将它们存储在一个数组中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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按
按价格升序排列房屋:
1 2 3 | homes.sort(function(a, b) { return parseFloat(a.price) - parseFloat(b.price); }); |
或在ES6版本之后:
1 | homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price)); |
这里可以找到一些文档。
这里有一个更灵活的版本,允许您创建可重用的排序函数,并按任何字段排序。
1 2 3 4 5 6 7 8 9 10 11 12 | var sort_by = function(field, reverse, primer){ var 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)); } } |
现在您可以任意按字段排序…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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" }]; // Sort by price high to low homes.sort(sort_by('price', true, parseInt)); // Sort by city, case-insensitive, A-Z homes.sort(sort_by('city', false, function(a){return a.toUpperCase()})); |
要对其进行排序,需要创建一个带有两个参数的比较器函数。然后使用该比较器函数调用sort函数,如下所示:
1 2 3 4 5 | // 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); |
如果要升序排序,请切换减号两边的表达式。
如果有人需要字符串排序,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | var dataArr = { "hello": [{ "id": 114, "keyword":"zzzzzz", "region":"Sri Lanka", "supportGroup":"administrators", "category":"Category2" }, { "id": 115, "keyword":"aaaaa", "region":"Japan", "supportGroup":"developers", "category":"Category2" }] }; var sortArray = dataArr['hello']; sortArray.sort(function(a,b) { if ( a.region < b.region ) return -1; if ( a.region > b.region ) return 1; return 0; } ); |
如果您有符合ES6的浏览器,则可以使用:
- 箭头函数
- number()函数
- SO()函数
升序和降序排序顺序的区别是比较函数返回值的符号:
1 2 | var ascending = homes.sort((a, b) => Number(a.price) - Number(b.price)); var descending = homes.sort((a, b) => Number(b.price) - Number(a.price)); |
下面是一个工作代码段:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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对它排序,对吗?您需要的是
1 2 3 4 5 6 | 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)); |
比较器获取数组中每个嵌套散列中的一个,并通过检查"price"字段确定哪个散列更高。
我推荐Github:array sortby-使用Schwartzian转换的
但是现在我们要尝试这个方法:sortby old.js.
让我们创建一个方法来排序数组,使其能够按某些属性排列对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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)); }); }; }()); |
设置未排序的数据
1 2 3 4 5 | var data = [ {date:"2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type:"tab <div class="suo-content">[collapse title=""]<ul><li>我添加了一个新的更强大的实现,允许多种排序,例如<wyn>field1</wyn>asc,<wyn>field2</wyn>desc,<wyn>field3</wyn>desc。新的<wyn>sortBy</wyn>方法是Schwartzian转换的实现,您可以在这里找到它:gist:sortby.js</li><li>当字段为空时,这似乎会中断。</li><li>@tsnev你能举个例子吗(jsiddle,plunkr,等等)?我试图复制它,但没有成功,<wyn>null</wyn>值是在数组末尾排序的。</li><li>如果您正在对数字进行排序,并且在对象数组之间遇到"0",则可能会注意到上面的代码中断。这里有一个快速修复方法:<wyn>var checkNaN = function (value) { return Number.isNaN(Number(value)) ? 0 : value; }</wyn>,后面是:返回函数(array,o)…..a=扢getitem.call(o,a);a=checknan(a);b=扢getitem.call(o,b);b=checknan(b);返回o.desc*(a<b?-1:+(a>b)););</li><li>感谢您对@ozesh的反馈,上面的<wyn>sortBy</wyn>版本已被弃用:)我为排序数组编写了一个新的更强大的实现。检查要点:Sortby</li><li>@Ozesh,在应用了你的建议之后,上面包含的测试失败了,例如<wyn>sortBy(data, { prop:"date" });</wyn>不起作用。你能给我提供一个普朗克,杰斯菲德尔,杰斯宾等的箱子吗?谢谢!</li><li>@Jherax,我已经用一些新的数据格式编辑了你以前的代码作为参考,你可以通过用旧的插件替换这个插件来比较它:这里是另一个:链接</li><li>@再次感谢你的反馈。我明白你的意思。但是,在测试了这个JSfiddle中建议的修复之后,失败了。我在处理具有错误值属性的对象时注意到了这个bug,比如<wyn>0, false,""</wyn>。这个bug在这个程序中被修复了,您也可以在gist:sortby中检查其他测试(已弃用)</li><li>@你的新插件比旧插件好得多。谢谢分享。</li></ul>[/collapse]</div><hr><P>使用lodash.sortby(使用commonjs的说明,您也可以将cdn的脚本include标签放在HTML的顶部)</P>[cc lang="javascript"]var sortBy = require('lodash.sortby'); // or sortBy = require('lodash').sortBy; |
降序
1 | var descendingOrder = sortBy( homes, 'price' ).reverse(); |
升序
1 | var ascendingOrder = sortBy( homes, 'price' ); |
这可以通过一个简单的单行valueof()排序函数来实现。运行下面的代码段以查看演示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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); |
如果使用underline.js,请尝试sortby:
1 2 3 4 5 | // price is of an integer type _.sortBy(homes,"price"); // price is of a string type _.sortBy(homes, function(home) {return parseInt(home.price);}); |
您可以将javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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); |
下面是上面所有答案的顶点。
小提琴验证:http://jsfiddle.net/bobberino/4qqk3/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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(); })); } } |
我还处理了一些评级和多个字段排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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); }); |
结果
1 2 3 4 5 6 7 8 9 10 | [ {"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} ] |
这是一个不错的jquery插件:
http://plugins.jquery.com/project/sort(返回机器链接)
虽然仅对单个数组进行排序有点过分,但此原型函数允许使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | (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); }; })(); |
用途:
1 2 3 4 5 6 7 8 9 10 | 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)" |
按具有点语法或数组语法的嵌套属性排序:
1 2 | 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)" |
按多个键排序:
1 2 | 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的答案可以更简洁:
1 | homes.sort((a, b) => a.price - b.price) |
仅限元素值的普通数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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] |
对于对象数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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}] |
我参加聚会有点晚,但下面是我整理东西的逻辑。
1 2 3 4 5 | function getSortedData(data, prop, isAsc){ return data.sort((a, b)=>{ return (a[prop] < b[prob] ? -1: 1 ) * (isAsc ? 1 : -1) }); } |
要对数组进行排序,必须定义一个比较器函数。此函数在所需的排序模式或顺序(即升序或降序)上总是不同的。
让我们创建一些函数来对数组进行升序或降序排序,这些函数包含对象、字符串或数值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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']); } |
对数字排序(按字母顺序和升序排列):
1 2 | var fruits = ["Banana","Orange","Apple","Mango"]; fruits.sort(); |
排序数字(按字母顺序和降序排列):
1 2 3 | var fruits = ["Banana","Orange","Apple","Mango"]; fruits.sort(); fruits.reverse(); |
排序数字(数字和升序):
1 2 | var points = [40,100,1,5,25,10]; points.sort(sorterAscending()); |
排序数字(数字和降序):
1 2 | var points = [40,100,1,5,25,10]; points.sort(sorterDescending()); |
如上所述,将sorterpriceasc和sorterpricedes方法与具有所需键的数组一起使用。
1 | homes.sort(sorterPriceAsc()) or homes.sort(sorterPriceDes()) |
这里是一个稍微修改过的优雅实现版本,来自于书"javascript:好的部分"。
注:此版本的
我已经向它添加了
可以按多个属性升序、降序和链排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | 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 <div class="suo-content">[collapse title=""]<ul><li>为什么我的答案社区wiki?</li><li>我们可以按ID对数组的<wyn>{"first":"Curly","last":"Howard","property" : {"id" :"1"}}</wyn>类型进行排序吗?</li><li>是的,函数必须稍微修改一下才能接受一个新的参数,比如说nestedname。然后用name="property",nestedname="id"调用<wyn>by</wyn>。</li></ul>[/collapse]</div><hr><P>你需要两个功能</P>[cc lang="javascript"]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; } |
然后您可以将此应用于任何对象属性:
1 | data.sort((a, b) => desc(parseFloat(a.price), parseFloat(b.price))); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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', 'DESCending sorted[cc lang="javascript"]' + JSON.stringify(data) +' |
;/ASCdata.sort((a,b)=>asc(a.value,b.value));document.body.insertadjacenthtml文档.body.insertadjacenthtml("提前"'升序排序
1 | ' + JSON.stringify(data) +' |
';
虽然我知道OP想要对一组数字进行排序,但这个问题已被标记为关于字符串的类似问题的答案。对于这一事实,上述答案不考虑在大小写很重要的地方对文本数组进行排序。大多数答案采用字符串值并将其转换为大写/小写,然后以某种方式进行排序。我坚持的要求很简单:
- 按字母顺序A-Z排序
- 同一单词的大写值应在小写值之前
- 应将相同的字母(A/A、B/B)值组合在一起
我期望的是
1 2 3 | 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" ] |
这会告诉函数将大小写值排序在小写值之前。
这同样适用于对对象数组进行排序:
1 2 3 4 5 6 7 8 9 10 11 12 | 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" })); |
使用下面的代码创建一个函数并根据输入进行排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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); |
我最近写了一个通用函数来管理这个问题,如果你想使用它的话。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | /** * 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); } |
嗨,在阅读本文之后,我为我的需要制作了一个sortComparator,它具有比较多个JSON属性的功能,我想与您共享它。
该解决方案只按升序比较字符串,但该解决方案可以很容易地扩展到每个要支持的属性:反向排序、其他数据类型、使用区域设置、强制转换等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 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); }); |
结果是
1 2 3 4 | $ node sort 4 Bevery Hills CA 90210 319250 5 New York NY 00010 962500 3 Dallas TX 75201 162500 |
还有另一种
1 2 3 | homes.sort(function(a, b) { return sortComparator(a, b, ['city', 'zip']); }); |
以结果
1 2 3 4 | $ node sort 4 Bevery Hills CA 90210 319250 3 Dallas TX 75201 162500 5 New York NY 00010 962500 |
For sort on multiple array object field.
Enter your field name in
then pass in second parameter
1 2 3 4 5 6 7 8 | 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; } |
1 2 3 4 5 6 7 8 | 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) }) |