Say I have an array of Person objects:
var people = [{name: "Joe Schmo", age: 36}, {name: "JANE DOE", age: 40}];
and I have a function which can sort an array of strings case insensitively:
function caseInsensitiveSort(arr) { ... }
Is there any straightforward way to combine my existing sort function with Array.prototype.map to sort the people array just using the name key?
I.e. it would produce
var people = [{name: "JANE DOE", age: 40}, {name: "Joe Schmo", age: 36}];
Doing it by hand is not hard in this particular case,
people.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
but I can't think of a way of doing it that would allow me to use the pre-existing sort function. In a case where the sort function is more customized, that would be useful.
Edit: I believe that the core problem here is that to do this well, you need to be able to figure out what the original indices were mapped to when you sort the proxy array. Getting those new indices using JS's native sort function does not seem possible in the general case. But I'd be happy to be proven wrong.
Edit: The way I was trying to do this is too inefficient to be useful. See the answer below for the solution using a comparison function instead.
caseInsensitiveSortaccepts an array, you would need to pass an array of the names to that function, sort the names, and then sort the array with the objects based on the array with the names. Sounds like a really complicated way to do something simple.Array.prototype.mapmethod creates a new array, so with millions of records the best option is to sort it in-place.Array.prototype.sort, rather than trying to wedge my sort function in.