Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  32] [ 6]  / answers: 1 / hits: 40326  / 13 Years ago, fri, december 16, 2011, 12:00:00

I'm trying to sort an array of objects. I'd prefer not to write a custom sort method for each attribute.



Is there anyway I could extend the built-in array.sort() method to accept an extra parameter, describing the attribute to sort on? E.g.,



array.sort(function(a, b, attr) { return a.attr - b.attr; }, 'name');

More From » sorting

 Answers
63

Write a function generator that accepts a property name:



function propComparator(prop) {
return function(a, b) {
return a[prop] - b[prop];
}
}

arr.sort(propComparator('name'));


You can also save the sorters for later use, directly, or as parameters:



var compareNames = propComparator('name');
var compareFoos = propComparator('foo');
...
arr.sort(compareNames);
takesComparator(compareFoos);


Updated for ES6, and make it so it actually works with different types.



Note that sort sorts in-place, which may or may not be desirable.





const arr = [
{ name: 'John', age: 92 },
{ name: 'Dave', age: 42 },
{ name: 'Justin', age: 3 }
]

const propComparator = (propName) =>
(a, b) => a[propName] == b[propName] ? 0 : a[propName] < b[propName] ? -1 : 1

arr.sort(propComparator('name'))
console.log(By name, arr)

arr.sort(propComparator('age'))
console.log(By age, arr)




[#88522] Thursday, December 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dequant

Total Points: 88
Total Questions: 99
Total Answers: 95

Location: Ukraine
Member since Sun, Dec 13, 2020
4 Years ago
dequant questions
;