Javascript 根据数组的一个属性按字母顺序对数组中的对象进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8900732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort objects in an array alphabetically on one property of the array
提问by jdavis
Let's say you have a JavaScript class like this
假设你有一个这样的 JavaScript 类
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
Let's say you then create a number of instances of that class and store them in an array
假设您然后创建了该类的多个实例并将它们存储在一个数组中
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}));
So I now would have an array of objects created by DepartmentFactory
. How would I go about using the array.sort()
method to sort this array of objects by the DepartmentName
property of each object?
所以我现在会有一个由DepartmentFactory
. 我将如何使用该array.sort()
方法按DepartmentName
每个对象的属性对这个对象数组进行排序?
The array.sort()
method works just fine when sorting an array of strings
该array.sort()
方法在对字符串数组进行排序时工作得很好
var myarray=["Bob", "Bully", "Amy"];
myarray.sort(); //Array now becomes ["Amy", "Bob", "Bully"]
But how do I make it work with a list of objects?
但是我如何使它与对象列表一起工作?
回答by Omer Bokhari
you would have to do something like this:
你必须做这样的事情:
objArray.sort(function(a, b) {
var textA = a.DepartmentName.toUpperCase();
var textB = b.DepartmentName.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
note: changing the case (to upper or lower) ensures a case insensitive sort.
注意:更改大小写(为大写或小写)可确保不区分大小写的排序。
回答by ron tornambe
To support unicode:
支持unicode:
objArray.sort(function(a, b) {
return a.DepartmentName.localeCompare(b.DepartmentName);
});
回答by Diode
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);
回答by bob
// 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
*/
回答by qwertymk
DEMO
演示
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}));
回答by Neil
objArray.sort((a, b) => a.DepartmentName.localeCompare(b.DepartmentName))
回答by nickleefly
do it like this
像这样做
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)
回答by Michael Norward
Here is a simple function you can use to sort array of objects through their properties; it doesn't matter if the property is a type of string or integer, it will work.
这是一个简单的函数,可用于通过对象的属性对对象数组进行排序;属性是字符串类型还是整数类型都没有关系,它会起作用。
var cars = [
{make:"AMC", model:"Pacer", year:1978},
{make:"Koenigsegg", model:"CCGT", year:2011},
{make:"Pagani", model:"Zonda", year:2006},
];
function sortObjectsByProp(objectsArr, prop, ascending = true) {
let objectsHaveProp = objectsArr.every(object => object.hasOwnProperty(prop));
if(objectsHaveProp) {
let newObjectsArr = objectsArr.slice();
newObjectsArr.sort((a, b) => {
if(isNaN(Number(a[prop]))) {
let textA = a[prop].toUpperCase(),
textB = b[prop].toUpperCase();
if(ascending) {
return textA < textB ? -1 : textA > textB ? 1 : 0;
} else {
return textB < textA ? -1 : textB > textA ? 1 : 0;
}
} else {
return ascending ? a[prop] - b[prop] : b[prop] - a[prop];
}
});
return newObjectsArr;
}
return objectsArr;
}
let sortedByMake = sortObjectsByProp(cars, "make"); // returns ascending order by its make;
let sortedByYear = sortObjectsByProp(cars, "year", false); // returns descending order by its year,since we put false as a third argument;
console.log(sortedByMake);
console.log(sortedByYear);
回答by Alissa
objArray.sort( (a, b) => a.id.localeCompare(b.id, 'en', {'sensitivity': 'base'}));
This sorts them alphabetically AND is case insensitive. It's also super clean and easy to read :D
这按字母顺序对它们进行排序并且不区分大小写。它也超级干净且易于阅读:D
回答by zconnelly13
You have to pass a function that accepts two parameters, compares them, and returns a number, so assuming you wanted to sort them by ID you would write...
您必须传递一个接受两个参数、比较它们并返回一个数字的函数,因此假设您想按 ID 对它们进行排序,您将编写...
objArray.sort(function(a,b) {
return a.id-b.id;
});
// objArray is now sorted by Id