如何根据javascript对象的属性对javascript对象进行排序,指定属性 [英] How to sort javascript objects based on their properties, specifying the property
问题描述
对于类似问题,SO上有很多答案,它们都描述了如何实现自定义排序函数来对javascript对象数组进行排序。
There are lots of answers on SO for similar questions, which all describe how to implement a custom sort function to sort an array of javascript objects.
但是,我我想知道是否有可能实现一个更抽象的自定义排序,它允许我传递我想要它排序的对象的属性名称。这可能会让我不得不一遍又一遍地实现非常相似的功能。
However, I was wondering if it might be possible to implement a more abstract custom sort that would allow me to pass the name of the property of the objects on which I want it to sort. This might save me having to implement very similar functions over and over again.
所以如果我有一个像这样的对象构造函数:
So if I had an object constructor like:
function Car(mph, cc) {
this.maxSpeed = mph;
this.engineSize = cc;
}
然后代替实现两个排序函数:
then instead of implementing two sort functions:
function sortCarsOnMaxSpeed(a, b) { return a.maxSpeed - b.maxSpeed; }
function sortCarsOnEngineSize(a, b) { return a.engineSize - b.engineSize; }
我可以使用某种泛型函数,例如:
I could have some sort of generic function such as:
function sortObjectsOnProperty(a, b, property) {
return a[property] - b[property];
}
但自定义排序似乎只占用2个参数。
but the custom sort seems to only take 2 arguments.
有关如何做到这一点的任何建议吗?
Any suggestions as to how I could do this?
非常感谢。
推荐答案
您需要编写一个带有属性名称并返回比较器的函数:
You need to write a function that takes a property name and returns a comparator:
function createComparator(property) {
return function(a, b) {
return a[property] - b[property];
};
}
您可以这样使用它:
arr.sort(createComparator("maxSpeed"));
这篇关于如何根据javascript对象的属性对javascript对象进行排序,指定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!