Any way to extend javascript's array.sort() method to accept another parameter?
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)
Is this what you're looking for?
function sortByProperty(array, propertyName) {
return array.sort(function (a, b) {
return a[propertyName] - b[propertyName];
});
}
var sortedByName = sortByProperty(myArray, "name");
Use prototypes to compare strings and numbers correctly
Array.prototype.sortAttr = function(attr,reverse) {
var sorter = function(a,b) {
var aa = a[attr];
var bb = b[attr];
if(aa+0==aa && bb+0==bb) return aa-bb; // numbers
else return aa.localeCompare(bb); // strings
}
this.sort(function(a,b) {
var result = sorter(a,b);
if(reverse) result*= -1;
return result;
});
};
Example
var data = [
{name: "Josh", age: 18},
{name: "John", age: 17},
{name: "Bob", age: 20},
{name: 0, age: "error"}
];
data.sortAttr("name");
// data is now sorted by name