admin管理员组文章数量:1355670
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];
}
but the custom sort seems to only take 2 arguments.
Any suggestions as to how I could do this?
Many thanks.
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];
}
but the custom sort seems to only take 2 arguments.
Any suggestions as to how I could do this?
Many thanks.
Share Improve this question asked Sep 18, 2011 at 16:23 JoeJoe 4,92810 gold badges67 silver badges85 bronze badges2 Answers
Reset to default 8You need to write a function that takes a property name and returns a parator:
function createComparator(property) {
return function(a, b) {
return a[property] - b[property];
};
}
You would use it like this:
arr.sort(createComparator("maxSpeed"));
sort
takes a function, which can be anonymous:
sort(array, function(a, b) { return a.maxSpeed - b.maxSpeed; });
If you really don't want this, you can define a sortObjectsOnProperty() function that return a sort callback like this:
function sortObjectsOnProperty(name) {
return function(a, b) { return a[name] - b[name]; }
}
本文标签:
版权声明:本文标题:sorting - How to sort javascript objects based on their properties, specifying the property - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744002142a2574055.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论