假设你有一个像这样的javascript类
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
假设您创建了该类的多个实例并将它们存储在数组中
var objArray = [];
objArray.push(DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));
所以我现在将拥有一个由DepartmentFactory
创建的对象数组。我如何使用array.sort()
方法按每个对象的DepartmentName
属性对这个对象数组进行排序?
array.sort()
方法在排序字符串数组时工作正常
var myarray=["Bob", "Bully", "Amy"];
myarray.sort(); //Array now becomes ["Amy", "Bob", "Bully"]
但是如何使它与对象列表一起使用?
答案 0 :(得分:263)
你必须做这样的事情:
objArray.sort(function(a, b) {
var textA = a.DepartmentName.toUpperCase();
var textB = b.DepartmentName.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
注意:更改大小写(向上或向下)可确保不区分大小写的排序。
答案 1 :(得分:122)
支持unicode:
objArray.sort(function(a, b) {
return a.DepartmentName.localeCompare(b.DepartmentName);
});
答案 2 :(得分:11)
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
// use `new DepartmentFactory` as given below. `new` is imporatant
var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));
function sortOn(property){
return function(a, b){
if(a[property] < b[property]){
return -1;
}else if(a[property] > b[property]){
return 1;
}else{
return 0;
}
}
}
//objArray.sort(sortOn("id")); // because `this.id = data.Id;`
objArray.sort(sortOn("name")); // because `this.name = data.DepartmentName;`
console.log(objArray);
答案 3 :(得分:8)
objArray.sort((a, b) => a.DepartmentName.localeCompare(b.DepartmentName))
答案 4 :(得分:5)
// Sorts an array of objects "in place". (Meaning that the original array will be modified and nothing gets returned.)
function sortOn (arr, prop) {
arr.sort (
function (a, b) {
if (a[prop] < b[prop]){
return -1;
} else if (a[prop] > b[prop]){
return 1;
} else {
return 0;
}
}
);
}
//Usage example:
var cars = [
{make:"AMC", model:"Pacer", year:1978},
{make:"Koenigsegg", model:"CCGT", year:2011},
{make:"Pagani", model:"Zonda", year:2006},
];
// ------- make -------
sortOn(cars, "make");
console.log(cars);
/* OUTPUT:
AMC : Pacer : 1978
Koenigsegg : CCGT : 2011
Pagani : Zonda : 2006
*/
// ------- model -------
sortOn(cars, "model");
console.log(cars);
/* OUTPUT:
Koenigsegg : CCGT : 2011
AMC : Pacer : 1978
Pagani : Zonda : 2006
*/
// ------- year -------
sortOn(cars, "year");
console.log(cars);
/* OUTPUT:
AMC : Pacer : 1978
Pagani : Zonda : 2006
Koenigsegg : CCGT : 2011
*/
答案 5 :(得分:4)
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));
console.log(objArray.sort(function(a, b) { return a.name > b.name}));
答案 6 :(得分:4)
ES6中的短代码
objArray.sort((a, b) => a.DepartmentName.toLowerCase().localeCompare(b.DepartmentName.toLowerCase()))
答案 7 :(得分:0)
这样做
objArrayy.sort(function(a, b){
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
if (nameA < nameB) //sort string ascending
return -1
if (nameA > nameB)
return 1
return 0 //default return value (no sorting)
});
console.log(objArray)
答案 8 :(得分:0)
objArray.sort( (a, b) => a.id.localeCompare(b.id, 'en', {'sensitivity': 'base'}));
这按字母顺序对它们进行排序,并且不区分大小写。它也很干净而且易于阅读:D
答案 9 :(得分:0)
这是一个简单的函数,可用于通过对象的属性对对象数组进行排序;不管该属性是字符串还是整数,都可以使用。
(width, height, nb_channels=3, max_pow+1)
答案 10 :(得分:0)
因为这里提供的所有解决方案都没有空/未定义的安全操作,所以我是这样处理的(您可以根据需要处理空值):
ES5
service.request(request).map { _ in () }.eraseToAnyPublisher()
ES6+
objArray.sort(
function(a, b) {
var departmentNameA = a.DepartmentName ? a.DepartmentName : '';
var departmentNameB = b.DepartmentName ? b.DepartmentName : '';
departmentNameA.localeCompare(departmentNameB);
}
);
我还删除了其他人使用的 toLowerCase,因为 localeCompare 不区分大小写。此外,我更喜欢在使用 Typescript 或 ES6+ 时对参数更加明确,以便为未来的开发人员提供更加明确的参数。
答案 11 :(得分:-1)
你必须传递一个接受两个参数的函数,比较它们并返回一个数字,所以假设你想按ID对它们进行排序,你会写...
objArray.sort(function(a,b) {
return a.id-b.id;
});
// objArray is now sorted by Id
答案 12 :(得分:-2)
尝试了一下,并尝试减少循环次数后,我得到了以下解决方案:
const items = [
{
name: 'One'
},
{
name: 'Maria is here'
},
{
name: 'Another'
},
{
name: 'Z with a z'
},
{
name: '1 number'
},
{
name: 'Two not a number'
},
{
name: 'Third'
},
{
name: 'Giant'
}
];
const sorted = items.sort((a, b) => {
return a[name] > b[name];
});
let sortedAlphabetically = {};
for(var item in sorted) {
const firstLetter = sorted[item].name[0];
if(sortedAlphabetically[firstLetter]) {
sortedAlphabetically[firstLetter].push(sorted[item]);
} else {
sortedAlphabetically[firstLetter] = [sorted[item]];
}
}
console.log('sorted', sortedAlphabetically);
答案 13 :(得分:-3)
一个简单的答案:
objArray.sort(function(obj1, obj2) {
return obj1.DepartmentName > obj2.DepartmentName;
});
ES6方式:
objArray.sort((obj1, obj2) => {return obj1.DepartmentName > obj2.DepartmentName};
如果你需要将它设置为小写/大写等,只需这样做并将结果存储在变量中,而不是比较该变量。示例:
objArray.sort((obj1, obj2) => {
var firstObj = obj1.toLowerCase();
var secondObj = obj2.toLowerCase();
return firstObj.DepartmentName > secondObj.DepartmentName;
});