从这个original question开始,我将如何对多个字段应用排序?
使用这种略微适应的结构,我如何排序城市(升序)&价格(下降)?
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":"6",
"city":"Dallas",
"state":"TX",
"zip":"75000",
"price":"556699"},
{"h_id":"5",
"city":"New York",
"state":"NY",
"zip":"00010",
"price":"962500"}
];
我喜欢这个事实而不是answer提供了一般方法。在我计划使用此代码的地方,我将不得不对日期以及其他内容进行排序。 “引导”物体的能力似乎很方便,如果不是有点麻烦。
我已经尝试将这个answer构建成一个很好的通用示例,但我没有太多运气。
答案 0 :(得分:87)
针对您的确切问题的非通用,简单的解决方案:
homes.sort(
function(a, b) {
if (a.city === b.city) {
// Price is only important when cities are the same
return b.price - a.price;
}
return a.city > b.city ? 1 : -1;
});
答案 1 :(得分:72)
多维排序方法based on this answer:
更新:这是一个“优化”版本。它进行了更多的预处理,并预先为每个排序选项创建了一个比较函数。它可能需要更多的内存(因为它为每个排序选项存储一个函数,但它应该预先形成一点,因为它不需要在比较期间确定正确的设置。我没有做过任何分析。
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;
}
}
}());
使用示例:
homes.sort(sort_by('city', {name:'price', primer: parseInt, reverse: true}));
原创功能:
var sort_by = function() {
var fields = [].slice.call(arguments),
n_fields = fields.length;
return function(A,B) {
var a, b, field, key, primer, reverse, result, i;
for(i = 0; i < n_fields; i++) {
result = 0;
field = fields[i];
key = typeof field === 'string' ? field : field.name;
a = A[key];
b = B[key];
if (typeof field.primer !== 'undefined'){
a = field.primer(a);
b = field.primer(b);
}
reverse = (field.reverse) ? -1 : 1;
if (a<b) result = reverse * -1;
if (a>b) result = reverse * 1;
if(result !== 0) break;
}
return result;
}
};
答案 2 :(得分:35)
这是一个简单的功能方法。使用数组指定排序顺序。在减去前面加上指定降序。
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":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":"556699"},
{"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":"962500"}
];
homes.sort(fieldSorter(['city', '-price']));
// homes.sort(fieldSorter(['zip', '-state', 'price'])); // alternative
function fieldSorter(fields) {
return function (a, b) {
return fields
.map(function (o) {
var dir = 1;
if (o[0] === '-') {
dir = -1;
o=o.substring(1);
}
if (a[o] > b[o]) return dir;
if (a[o] < b[o]) return -(dir);
return 0;
})
.reduce(function firstNonZeroValue (p,n) {
return p ? p : n;
}, 0);
};
}
在ES6中编辑它甚至更短!
"use strict";
const fieldSorter = (fields) => (a, b) => fields.map(o => {
let dir = 1;
if (o[0] === '-') { dir = -1; o=o.substring(1); }
return a[o] > b[o] ? dir : a[o] < b[o] ? -(dir) : 0;
}).reduce((p, n) => p ? p : n, 0);
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":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":556699},{"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":962500}];
const sortedHomes = homes.sort(fieldSorter(['state', '-price']));
document.write('<pre>' + JSON.stringify(sortedHomes, null, '\t') + '</pre>')
&#13;
答案 3 :(得分:29)
我今天做了一个非常通用的多功能分拣机。你可以在这里查看thenBy.js:https://github.com/Teun/thenBy.js
它允许您使用标准的Array.sort,但使用firstBy()。thenBy()。thenBy()样式。它比上面发布的解决方案更少的代码和复杂性。
答案 4 :(得分:11)
以下函数将允许您对一个或多个属性上的对象数组进行排序,可以是升序(默认),也可以是降序每个属性,并允许您选择是否执行区分大小写的比较。默认情况下,此函数执行不区分大小写的排序。
第一个参数必须是包含对象的数组。
后续参数必须是以逗号分隔的字符串列表,这些字符串引用要排序的不同对象属性。最后一个参数(可选)是一个布尔值,用于选择是否执行区分大小写的排序 - 使用true
进行区分大小写的排序。
该函数默认按升序对每个属性/键进行排序。如果您希望特定键按降序排序,则使用以下格式传递数组:['property_name', true]
。
以下是函数的一些示例用法,后面是解释(其中homes
是包含对象的数组):
objSort(homes, 'city')
- &gt;按城市排序(升序,案例不敏感)
objSort(homes, ['city', true])
- &gt;按城市排序(降序,案例不敏感)
objSort(homes, 'city', true)
- &gt;按城市排序然后定价(升序,案例敏感)
objSort(homes, 'city', 'price')
- &gt;按城市排序然后按价格(升序,案例不敏感)
objSort(homes, 'city', ['price', true])
- &gt;按城市排序(升序)然后按价格(降序),案例不敏感)
不用多说,这就是功能:
function objSort() {
var args = arguments,
array = args[0],
case_sensitive, keys_length, key, desc, a, b, i;
if (typeof arguments[arguments.length - 1] === 'boolean') {
case_sensitive = arguments[arguments.length - 1];
keys_length = arguments.length - 1;
} else {
case_sensitive = false;
keys_length = arguments.length;
}
return array.sort(function (obj1, obj2) {
for (i = 1; i < keys_length; i++) {
key = args[i];
if (typeof key !== 'string') {
desc = key[1];
key = key[0];
a = obj1[args[i][0]];
b = obj2[args[i][0]];
} else {
desc = false;
a = obj1[args[i]];
b = obj2[args[i]];
}
if (case_sensitive === false && typeof a === 'string') {
a = a.toLowerCase();
b = b.toLowerCase();
}
if (! desc) {
if (a < b) return -1;
if (a > b) return 1;
} else {
if (a > b) return -1;
if (a < b) return 1;
}
}
return 0;
});
} //end of objSort() function
以下是一些示例数据:
var homes = [{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": 162500
}, {
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": 1000000
}, {
"h_id": "5",
"city": "new york",
"state": "NY",
"zip": "00010",
"price": 1000000
}, {
"h_id": "6",
"city": "Dallas",
"state": "TX",
"zip": "85000",
"price": 300000
}, {
"h_id": "7",
"city": "New York",
"state": "NY",
"zip": "00020",
"price": 345000
}];
答案 5 :(得分:7)
这是另一个可能更接近你的语法
的想法function sortObjects(objArray, properties /*, primers*/) {
var primers = arguments[2] || {}; // primers are optional
properties = properties.map(function(prop) {
if( !(prop instanceof Array) ) {
prop = [prop, 'asc']
}
if( prop[1].toLowerCase() == 'desc' ) {
prop[1] = -1;
} else {
prop[1] = 1;
}
return prop;
});
function valueCmp(x, y) {
return x > y ? 1 : x < y ? -1 : 0;
}
function arrayCmp(a, b) {
var arr1 = [], arr2 = [];
properties.forEach(function(prop) {
var aValue = a[prop[0]],
bValue = b[prop[0]];
if( typeof primers[prop[0]] != 'undefined' ) {
aValue = primers[prop[0]](aValue);
bValue = primers[prop[0]](bValue);
}
arr1.push( prop[1] * valueCmp(aValue, bValue) );
arr2.push( prop[1] * valueCmp(bValue, aValue) );
});
return arr1 < arr2 ? -1 : 1;
}
objArray.sort(function(a, b) {
return arrayCmp(a, b);
});
}
// just for fun use this to reverse the city name when sorting
function demoPrimer(str) {
return str.split('').reverse().join('');
}
// Example
sortObjects(homes, ['city', ['price', 'desc']], {city: demoPrimer});
演示:http://jsfiddle.net/Nq4dk/2/
编辑:只是为了好玩,here's a variation只需要一个类似sql的字符串,所以你可以sortObjects(homes, "city, price desc")
function sortObjects(objArray, properties /*, primers*/) {
var primers = arguments[2] || {};
properties = properties.split(/\s*,\s*/).map(function(prop) {
prop = prop.match(/^([^\s]+)(\s*desc)?/i);
if( prop[2] && prop[2].toLowerCase() === 'desc' ) {
return [prop[1] , -1];
} else {
return [prop[1] , 1];
}
});
function valueCmp(x, y) {
return x > y ? 1 : x < y ? -1 : 0;
}
function arrayCmp(a, b) {
var arr1 = [], arr2 = [];
properties.forEach(function(prop) {
var aValue = a[prop[0]],
bValue = b[prop[0]];
if( typeof primers[prop[0]] != 'undefined' ) {
aValue = primers[prop[0]](aValue);
bValue = primers[prop[0]](bValue);
}
arr1.push( prop[1] * valueCmp(aValue, bValue) );
arr2.push( prop[1] * valueCmp(bValue, aValue) );
});
return arr1 < arr2 ? -1 : 1;
}
objArray.sort(function(a, b) {
return arrayCmp(a, b);
});
}
答案 6 :(得分:5)
这是一个完整的作弊,但我认为它增加了这个问题的价值,因为它基本上是一个罐头库函数,你可以开箱即用。
如果您的代码可以访问lodash
或lodash兼容的库,例如underscore
,那么您可以使用_.sortBy
方法。下面的代码段直接从lodash documentation复制。
示例中的注释结果看起来像是返回数组的数组,但这只是显示顺序,而不是实际结果,它们是一个对象数组。
var users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 34 }
];
_.sortBy(users, [function(o) { return o.user; }]);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
_.sortBy(users, ['user', 'age']);
// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
答案 7 :(得分:4)
您可以使用链式排序方法,取值的增量,直到达到不等于零的值。
var data = [{ 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: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];
data.sort(function (a, b) {
return a.city.localeCompare(b.city) || b.price - a.price;
});
console.log(data);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
或者,使用es6,只需:
data.sort(a, b => a.city.localeCompare(b.city) || b.price - a.price);
答案 8 :(得分:4)
更简单:
<!DOCTYPE html>
<!--[if !IE]><!-->
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<script src="/Metronic/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-cookies.min.js"></script>
<script src="/Scripts/angular-resource.min.js"></script>
<script src="/Scripts/angular-sanitize.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/Scripts/angular-ui-router.min.js"></script>
<script src="/Angular/app.js"></script>
<script src="/Angular/controllers.js"></script>
<script src="/Scripts/angular-local-storage.min.js"></script>
<script src="/Scripts/loading-bar.min.js"></script>
<script src="/Angular/Services/authInterceptorService.js"></script>
</head>
<body class="login">
<div class="content" ng-app="app">
<!-- BEGIN REGISTRATION FORM -->
<div class="register-form" ng-controller="signupController">
<h3 class="font-green">Sign Up</h3>
<p class="hint"> Enter your account details below: </p>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Email</label>
<input class="form-control placeholder-no-fix" ng-model="registration.Email" type="text" autocomplete="off" placeholder="Email" name="username" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control placeholder-no-fix" ng-model="registration.Password" type="password" autocomplete="off" id="register_password" placeholder="Password" name="password" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Re-type Your Password</label>
<input class="form-control placeholder-no-fix" ng-model="registration.ConfirmPassword" type="password" autocomplete="off" placeholder="Re-type Your Password" name="rpassword" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Role</label>
<select name="role" ng-change="CheckRole()" ng-model="registration.Role" class="form-control">
<option value="">Role</option>
<option value="Borrower">Borrower</option>
<option value="Introducer">Introducer</option>
<option value="Investor">Investor</option>
<option value="Valuer">Valuer</option>
</select>
</div>
<div class="form-actions">
<button type="button" id="register-back-btn" class="btn green btn-outline">Back</button>
<button type="submit" id="register-submit-btn" class="btn btn-success uppercase pull-right" ng-click="signUp()" ng-disabled="isProcessing" value="{{RegisterBtnText}}">
Submit
</button>
</div>
</div>
<!-- END REGISTRATION FORM -->
</div>
</body>
</html>
答案 9 :(得分:3)
我喜欢SnowBurnt的方法,但需要通过调整来测试城市的等价性而不是差异。
homes.sort(
function(a,b){
if (a.city==b.city){
return (b.price-a.price);
} else {
return (a.city-b.city);
}
});
答案 10 :(得分: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":"6",
"city":"Dallas",
"state":"TX",
"zip":"75000",
"price":"556699"},
{"h_id":"5",
"city":"New York",
"state":"NY",
"zip":"00010",
"price":"962500"}
];
function sortBy(ar) {
return ar.sort((a, b) => a.city === b.city ?
b.price.toString().localeCompare(a.price) :
a.city.toString().localeCompare(b.city));
}
console.log(sortBy(homes));
答案 11 :(得分:1)
以下是基于Schwartzian transform idiom的解决方案,希望您觉得它很有用。
function sortByAttribute(array, ...attrs) {
// generate an array of predicate-objects contains
// property getter, and descending indicator
let predicates = attrs.map(pred => {
let descending = pred.charAt(0) === '-' ? -1 : 1;
pred = pred.replace(/^-/, '');
return {
getter: o => o[pred],
descend: descending
};
});
// schwartzian transform idiom implementation. aka: "decorate-sort-undecorate"
return array.map(item => {
return {
src: item,
compareValues: predicates.map(predicate => predicate.getter(item))
};
})
.sort((o1, o2) => {
let i = -1, result = 0;
while (++i < predicates.length) {
if (o1.compareValues[i] < o2.compareValues[i]) result = -1;
if (o1.compareValues[i] > o2.compareValues[i]) result = 1;
if (result *= predicates[i].descend) break;
}
return result;
})
.map(item => item.src);
}
以下是如何使用它的示例:
let games = [
{ name: 'Pako', rating: 4.21 },
{ name: 'Hill Climb Racing', rating: 3.88 },
{ name: 'Angry Birds Space', rating: 3.88 },
{ name: 'Badland', rating: 4.33 }
];
// sort by one attribute
console.log(sortByAttribute(games, 'name'));
// sort by mupltiple attributes
console.log(sortByAttribute(games, '-rating', 'name'));
答案 12 :(得分:1)
以下是@ Snowburnt解决方案的通用版本:
var sortarray = [{field:'city', direction:'asc'}, {field:'price', direction:'desc'}];
array.sort(function(a,b){
for(var i=0; i<sortarray.length; i++){
retval = a[sortarray[i].field] < b[sortarray[i].field] ? -1 : a[sortarray[i].field] > b[sortarray[i].field] ? 1 : 0;
if (sortarray[i].direction == "desc") {
retval = retval * -1;
}
if (retval !== 0) {
return retval;
}
}
}
})
这是基于我正在使用的排序例程。我没有测试这个特定的代码,所以它可能有错误,但你明白了。我们的想法是根据指示差异的第一个字段进行排序,然后停止并转到下一个记录。因此,如果您按三个字段进行排序,并且比较中的第一个字段足以确定要排序的两个记录的排序顺序,则返回该排序结果并转到下一个记录。
我在5000条记录上测试了它(实际上有一点点复杂的排序逻辑)并且它在眨眼间就完成了。如果您实际上向客户端加载了超过1000条记录,那么您应该使用服务器端排序和过滤。
此代码并不处理区分大小写,但我将其留给读者来处理这个微不足道的修改。
答案 13 :(得分:0)
function sortMultiFields(prop){
return function(a,b){
for(i=0;i<prop.length;i++)
{
var reg = /^\d+$/;
var x=1;
var field1=prop[i];
if(prop[i].indexOf("-")==0)
{
field1=prop[i].substr(1,prop[i].length);
x=-x;
}
if(reg.test(a[field1]))
{
a[field1]=parseFloat(a[field1]);
b[field1]=parseFloat(b[field1]);
}
if( a[field1] > b[field1])
return x;
else if(a[field1] < b[field1])
return -x;
}
}
}
如何使用(如果要按特定字段的降序排序,请在字段前设置 - (减号))
homes.sort(sortMultiFields(["city","-price"]));
使用上面的函数,您可以使用多个字段对任何json数组进行排序。 根本不需要更改功能体
答案 14 :(得分:0)
这是一种递归算法,用于按多个字段排序,同时有机会在比较之前格式化值。
var data = [
{
"id": 1,
"ship": null,
"product": "Orange",
"quantity": 7,
"price": 92.08,
"discount": 0
},
{
"id": 2,
"ship": "2017-06-14T23:00:00.000Z".toDate(),
"product": "Apple",
"quantity": 22,
"price": 184.16,
"discount": 0
},
...
]
var sorts = ["product", "quantity", "ship"]
// comp_val formats values and protects against comparing nulls/undefines
// type() just returns the variable constructor
// String.lower just converts the string to lowercase.
// String.toDate custom fn to convert strings to Date
function comp_val(value){
if (value==null || value==undefined) return null
var cls = type(value)
switch (cls){
case String:
return value.lower()
}
return value
}
function compare(a, b, i){
i = i || 0
var prop = sorts[i]
var va = comp_val(a[prop])
var vb = comp_val(b[prop])
// handle what to do when both or any values are null
if (va == null || vb == null) return true
if ((i < sorts.length-1) && (va == vb)) {
return compare(a, b, i+1)
}
return va > vb
}
var d = data.sort(compare);
console.log(d);
如果a和b相等,则将尝试下一个字段,直到没有可用的字段为止。
答案 15 :(得分:0)
另一个选择。考虑使用以下实用程序功能:
/** Performs comparing of two items by specified properties
* @param {Array} props for sorting ['name'], ['value', 'city'], ['-date']
* to set descending order on object property just add '-' at the begining of property
*/
export const compareBy = (...props) => (a, b) => {
for (let i = 0; i < props.length; i++) {
const ascValue = props[i].startsWith('-') ? -1 : 1;
const prop = props[i].startsWith('-') ? props[i].substr(1) : props[i];
if (a[prop] !== b[prop]) {
return a[prop] > b[prop] ? ascValue : -ascValue;
}
}
return 0;
};
用法示例(在您的情况下):
homes.sort(compareBy('city', '-price'));
应该注意的是,为了能够使用嵌套的属性(例如“ address.city”或“ style.size.width”等),该功能甚至可以进一步推广。
答案 16 :(得分:0)
这是一种通用的多维排序,允许在每个级别上进行反转和/或映射。
用打字稿写。对于Javascript,请查看此JSFiddle
type itemMap = (n: any) => any;
interface SortConfig<T> {
key: keyof T;
reverse?: boolean;
map?: itemMap;
}
export function byObjectValues<T extends object>(keys: ((keyof T) | SortConfig<T>)[]): (a: T, b: T) => 0 | 1 | -1 {
return function(a: T, b: T) {
const firstKey: keyof T | SortConfig<T> = keys[0];
const isSimple = typeof firstKey === 'string';
const key: keyof T = isSimple ? (firstKey as keyof T) : (firstKey as SortConfig<T>).key;
const reverse: boolean = isSimple ? false : !!(firstKey as SortConfig<T>).reverse;
const map: itemMap | null = isSimple ? null : (firstKey as SortConfig<T>).map || null;
const valA = map ? map(a[key]) : a[key];
const valB = map ? map(b[key]) : b[key];
if (valA === valB) {
if (keys.length === 1) {
return 0;
}
return byObjectValues<T>(keys.slice(1))(a, b);
}
if (reverse) {
return valA > valB ? -1 : 1;
}
return valA > valB ? 1 : -1;
};
}
按姓氏,然后按名字排序人数组:
interface Person {
firstName: string;
lastName: string;
}
people.sort(byObjectValues<Person>(['lastName','firstName']));
按语言代码的名称 而不是其语言代码(请参见map
),然后按降序使用版本(请参见reverse
)。
interface Language {
code: string;
version: number;
}
// languageCodeToName(code) is defined elsewhere in code
languageCodes.sort(byObjectValues<Language>([
{
key: 'code',
map(code:string) => languageCodeToName(code),
},
{
key: 'version',
reverse: true,
}
]));
答案 17 :(得分:0)
适应@chriskelly的回答。
大多数答案都忽略了如果价值在一万或更低或超过一百万的情况下价格将无法正确排序。 JS的重新排序按字母顺序排序。在这里得到了很好的回答,Why can't JavaScript sort "5, 10, 1"和How to sort an array of integers correctly。
最终,如果我们排序的字段或节点是一个数字,我们必须做一些评估。我不是说在这种情况下使用parseInt()
是正确答案,排序结果更重要。
var homes = [{
"h_id": "2",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "62500"
}, {
"h_id": "1",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "62510"
}, {
"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": "6",
"city": "Dallas",
"state": "TX",
"zip": "75000",
"price": "556699"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}];
homes.sort(fieldSorter(['price']));
// homes.sort(fieldSorter(['zip', '-state', 'price'])); // alternative
function fieldSorter(fields) {
return function(a, b) {
return fields
.map(function(o) {
var dir = 1;
if (o[0] === '-') {
dir = -1;
o = o.substring(1);
}
if (!parseInt(a[o]) && !parseInt(b[o])) {
if (a[o] > b[o]) return dir;
if (a[o] < b[o]) return -(dir);
return 0;
} else {
return dir > 0 ? a[o] - b[o] : b[o] - a[o];
}
})
.reduce(function firstNonZeroValue(p, n) {
return p ? p : n;
}, 0);
};
}
document.getElementById("output").innerHTML = '<pre>' + JSON.stringify(homes, null, '\t') + '</pre>';
<div id="output">
</div>
答案 18 :(得分:0)
function sortByPriority(data, priorities) {
if (priorities.length == 0) {
return data;
}
const nextPriority = priorities[0];
const remainingPriorities = priorities.slice(1);
const matched = data.filter(item => item.hasOwnProperty(nextPriority));
const remainingData = data.filter(item => !item.hasOwnProperty(nextPriority));
return sortByPriority(matched, remainingPriorities)
.sort((a, b) => (a[nextPriority] > b[nextPriority]) ? 1 : -1)
.concat(sortByPriority(remainingData, remainingPriorities));
}
以下是您如何使用它的示例。
const data = [
{ id: 1, mediumPriority: 'bbb', lowestPriority: 'ggg' },
{ id: 2, highestPriority: 'bbb', mediumPriority: 'ccc', lowestPriority: 'ggg' },
{ id: 3, mediumPriority: 'aaa', lowestPriority: 'ggg' },
];
const priorities = [
'highestPriority',
'mediumPriority',
'lowestPriority'
];
const sorted = sortByPriority(data, priorities);
首先按属性的优先级排序,然后按属性的值排序。
答案 19 :(得分:0)
我一直在寻找类似的东西,最后得到了这个:
首先,我们有一个或多个排序函数,总是返回0、1或-1:
const sortByTitle = (a, b): number =>
a.title === b.title ? 0 : a.title > b.title ? 1 : -1;
您可以为要排序的每个其他属性创建更多功能。
然后我有一个将这些排序功能组合为一个的功能:
const createSorter = (...sorters) => (a, b) =>
sorters.reduce(
(d, fn) => (d === 0 ? fn(a, b) : d),
0
);
这可用于以可读的方式组合上述排序功能:
const sorter = createSorter(sortByTitle, sortByYear)
items.sort(sorter)
当排序函数返回0时,将调用下一个排序函数以进行进一步的排序。
答案 20 :(得分:0)
这是一种按多个字段排序的可扩展方式。
homes.sort(function(left, right) {
var city_order = left.city.localeCompare(right.city);
var price_order = parseInt(left.price) - parseInt(right.price);
return city_order || -price_order;
});
注释
a.localeCompare(b)
为universally supported,如果a<b
,a==b
,a>b
分别返回-1,0,1。||
比city
优先price
。-price_order
var date_order = new Date(left.date) - new Date(right.date);
就像数字一样,因为自{1970年以来date math变成了毫秒。return city_order || -price_order || date_order;
答案 21 :(得分:0)
我认为这可能是最简单的方法。
https://coderwall.com/p/ebqhca/javascript-sort-by-two-fields
这真的很简单,我尝试了3种不同的键值对,并且效果很好。
这是一个简单的示例,请查看链接以获取更多详细信息
testSort(data) {
return data.sort(
a['nameOne'] > b['nameOne'] ? 1
: b['nameOne'] > a['nameOne'] ? -1 : 0 ||
a['date'] > b['date'] ||
a['number'] - b['number']
);
}
答案 22 :(得分:0)
以下是我的供您参考:
function msort(arr, ...compFns) {
let fn = compFns[0];
arr = [].concat(arr);
let arr1 = [];
while (arr.length > 0) {
let arr2 = arr.splice(0, 1);
for (let i = arr.length; i > 0;) {
if (fn(arr2[0], arr[--i]) === 0) {
arr2 = arr2.concat(arr.splice(i, 1));
}
}
arr1.push(arr2);
}
arr1.sort(function (a, b) {
return fn(a[0], b[0]);
});
compFns = compFns.slice(1);
let res = [];
arr1.map(a1 => {
if (compFns.length > 0) a1 = msort(a1, ...compFns);
a1.map(a2 => res.push(a2));
});
return res;
}
let tstArr = [{ id: 1, sex: 'o' }, { id: 2, sex: 'm' }, { id: 3, sex: 'm' }, { id: 4, sex: 'f' }, { id: 5, sex: 'm' }, { id: 6, sex: 'o' }, { id: 7, sex: 'f' }];
function tstFn1(a, b) {
if (a.sex > b.sex) return 1;
else if (a.sex < b.sex) return -1;
return 0;
}
function tstFn2(a, b) {
if (a.id > b.id) return -1;
else if (a.id < b.id) return 1;
return 0;
}
console.log(JSON.stringify(msort(tstArr, tstFn1, tstFn2)));
//output:
//[{"id":7,"sex":"f"},{"id":4,"sex":"f"},{"id":5,"sex":"m"},{"id":3,"sex":"m"},{"id":2,"sex":"m"},{"id":6,"sex":"o"},{"id":1,"sex":"o"}]
答案 23 :(得分:0)
简单的解决方案:
items.sort((a, b) => {
const compare_name = a.name.localeCompare(b.name);
const compare_title = a.title.localeCompare(b.title);
const compare_city = a.city.localeCompare(b.city);
return compare_name || compare_title || compare_city;
});
如果您需要对更多字段进行排序,请添加更多||
答案 24 :(得分:-1)
这个简单的解决方案怎么样:
const sortCompareByCityPrice = (a, b) => {
let comparison = 0
// sort by first criteria
if (a.city > b.city) {
comparison = 1
}
else if (a.city < b.city) {
comparison = -1
}
// If still 0 then sort by second criteria descending
if (comparison === 0) {
if (parseInt(a.price) > parseInt(b.price)) {
comparison = -1
}
else if (parseInt(a.price) < parseInt(b.price)) {
comparison = 1
}
}
return comparison
}
答案 25 :(得分:-1)
对两个日期字段和数字字段示例进行排序:
var generic_date = new Date(2070, 1, 1);
checkDate = function(date) {
return Date.parse(date) ? new Date(date): generic_date;
}
function sortData() {
data.sort(function(a,b){
var deltaEnd = checkDate(b.end) - checkDate(a.end);
if(deltaEnd) return deltaEnd;
var deltaRank = a.rank - b.rank;
if (deltaRank) return deltaRank;
var deltaStart = checkDate(b.start) - checkDate(a.start);
if(deltaStart) return deltaStart;
return 0;
});
}
答案 26 :(得分:-1)
homes.sort(function(a,b) { return a.city - b.city } );
homes.sort(function(a,b){
if (a.city==b.city){
return parseFloat(b.price) - parseFloat(a.price);
} else {
return 0;
}
});
答案 27 :(得分:-1)
function sort(data, orderBy) {
orderBy = Array.isArray(orderBy) ? orderBy : [orderBy];
return data.sort((a, b) => {
for (let i = 0, size = orderBy.length; i < size; i++) {
const key = Object.keys(orderBy[i])[0],
o = orderBy[i][key],
valueA = a[key],
valueB = b[key];
if (!(valueA || valueB)) {
console.error("the objects from the data passed does not have the key '" + key + "' passed on sort!");
return [];
}
if (+valueA === +valueA) {
return o.toLowerCase() === 'desc' ? valueB - valueA : valueA - valueB;
} else {
if (valueA.localeCompare(valueB) > 0) {
return o.toLowerCase() === 'desc' ? -1 : 1;
} else if (valueA.localeCompare(valueB) < 0) {
return o.toLowerCase() === 'desc' ? 1 : -1;
}
}
}
});
}
使用:
sort(homes, [{city : 'asc'}, {price: 'desc'}])
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":"6",
"city":"Dallas",
"state":"TX",
"zip":"75000",
"price":"556699"},
{"h_id":"5",
"city":"New York",
"state":"NY",
"zip":"00010",
"price":"962500"}
];
function sort(data, orderBy) {
orderBy = Array.isArray(orderBy) ? orderBy : [orderBy];
return data.sort((a, b) => {
for (let i = 0, size = orderBy.length; i < size; i++) {
const key = Object.keys(orderBy[i])[0],
o = orderBy[i][key],
valueA = a[key],
valueB = b[key];
if (!(valueA || valueB)) {
console.error("the objects from the data passed does not have the key '" + key + "' passed on sort!");
return [];
}
if (+valueA === +valueA) {
return o.toLowerCase() === 'desc' ? valueB - valueA : valueA - valueB;
} else {
if (valueA.localeCompare(valueB) > 0) {
return o.toLowerCase() === 'desc' ? -1 : 1;
} else if (valueA.localeCompare(valueB) < 0) {
return o.toLowerCase() === 'desc' ? 1 : -1;
}
}
}
});
}
console.log(sort(homes, [{city : 'asc'}, {price: 'desc'}]));
答案 28 :(得分:-1)
此处&#39; AffiliateDueDate&#39;和&#39;标题&#39;是列,都按升序排序。
array.sort(function(a, b) {
if (a.AffiliateDueDate > b.AffiliateDueDate ) return 1;
else if (a.AffiliateDueDate < b.AffiliateDueDate ) return -1;
else if (a.Title > b.Title ) return 1;
else if (a.Title < b.Title ) return -1;
else return 0;
})
答案 29 :(得分:-3)
按多个字段对对象数组进行排序的最简单方法:
let 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":"6",
"city":"Dallas",
"state":"TX",
"zip":"75000",
"price":"556699"},
{"h_id":"5",
"city":"New York",
"state":"NY",
"zip":"00010",
"price":"962500"}
];
homes.sort((a, b) => (a.city > b.city) ? 1 : -1);
输出: “贝弗利山庄” “达拉斯” “达拉斯” “达拉斯” “纽约”