Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to extend javascript's array.sort() method to accept another parameter?

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'); 
like image 965
danwoods Avatar asked Dec 16 '11 17:12

danwoods


People also ask

How do you customize a sort function?

To define custom sort function, you need to compare first value with second value. If first value is greater than the second value, return -1. If first value is less than the second value, return 1 otherwise return 0. The above process will sort the data in descending order.

Does array sort modify the array?

A side effect of the sort method is that it changes the order of the elements in the original array. In other words, it mutates the array in place.

Can sort be applied to array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.


1 Answers

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)
like image 144
Dave Newton Avatar answered Oct 05 '22 20:10

Dave Newton