Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

sorting - How to sort javascript objects based on their properties, specifying the property

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];
    };
}

You would use it like this:

arr.sort(createComparator("maxSpeed"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...