在数组的一个属性上按字母顺序对数组中的对象进行排序 [英] Sort objects in an array alphabetically on one property of the array
问题描述
假设您有一个这样的JavaScript类
Let's say you have a JavaScript class like this
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}));
所以我现在将有一个由DepartmentFactory
创建的对象数组.我将如何使用array.sort()
方法通过每个对象的DepartmentName
属性对该对象数组进行排序?
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?
array.sort()
方法在对字符串数组进行排序时效果很好
The array.sort()
method works just fine when sorting an array of strings
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?
推荐答案
您将必须执行以下操作:
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.
这篇关于在数组的一个属性上按字母顺序对数组中的对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!