我找到了一个很好的方法来根据定义的属性之一对对象数组进行排序:
Sort array of objects by string property value in JavaScript
使用该函数非常适合单一排序(在所有浏览器上),甚至是另一种排序中的一种排序,除非使用 Google Chrome!这是 Ege Özcan 针对对象数组的出色排序例程
function dynamicSort(property) {
return function (a,b) {
return (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
}
}
使用名为“Data”的数组(当然,我的数组有更多的对象对)...
var Data = [{Category: "Business", Value: "ABC"},{Category:"Personal", Value:"XYZ"}];
通过执行此操作,我可以获得正确的排序,其中顺序列为每个类别中的所有值...
Data.sort(dynamicSort("Value"));
Data.sort(dynamicSort("Category"));
首先按Value
排序,然后按Category
排序,我的数组将所有值按排序顺序排列,首先列出所有业务基础值,然后列出所有个人值基于值。完美的!除了在 Chrome 中,数据按类别正确排序,但每个类别中值的顺序似乎相当随机。
有没有人知道在 Chrome 中也可以工作的排序中进行排序的更好方法?
最佳答案
我创建了该 dynamicSort 函数的多参数版本:
function dynamicSort(property) {
return function (obj1,obj2) {
return obj1[property] > obj2[property] ? 1
: obj1[property] < obj2[property] ? -1 : 0;
}
}
function dynamicSortMultiple() {
/*
* save the arguments object as it will be overwritten
* note that arguments object is an array-like object
* consisting of the names of the properties to sort by
*/
var props = arguments;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
/* try getting a different result from 0 (equal)
* as long as we have extra properties to compare
*/
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
}
}
我创建了一个数组如下:
var arr = [
{a:"a",b:"a",c:"a"},
{a:"b",b:"a",c:"b"},
{a:"b",b:"a",c:"a"},
{a:"b",b:"a",c:"b"},
{a:"b",b:"b",c:"a"},
{a:"b",b:"b",c:"b"},
{a:"b",b:"b",c:"a"},
{a:"b",b:"b",c:"b"},
{a:"b",b:"b",c:"a"},
{a:"b",b:"b",c:"b"},
{a:"b",b:"b",c:"a"},
{a:"c",b:"b",c:"b"},
{a:"c",b:"c",c:"a"}
];
当我这样做的时候它起作用了,
arr.sort(dynamicSortMultiple("c","b","a"));
这是一个工作示例:http://jsfiddle.net/ZXedp/
关于javascript - 如何在 JavaScript 中对具有多个字段值的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11379361/