简体   繁体   中英

Sort function that returns the same sorting

In the framework I'm using, I have to pass in a sort function for my array. The problem is that I don't want the sort to change. Is there a sort function that would return the exact same order?

Example:

var myObj= {
  myArray:['value2','value49','value16'],
  sort: function(a,b){}
}
myObj.myArray.sort(myObj.sort);

This is simplified but the sort function is required and will be executed on my array and I have no control over that. What would make it return the array in the exact same order?

Yes:

function () {return 0}

Just return 0 to leave the order unchanged for any pair of array elements. So, return it for all of them. The MDN docs for .sort() describe the method's behavior upon returning 0:

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM