Skip to content
Advertisement

Sort array on key value

I have a function which sorts by name currently and an array of value / key pairs.

I wonder how can I pass the key on which sort is being performed so I can call the same function every time like so:

JavaScript

Advertisement

Answer

[edit 2020/08/14] This was rather an old answer and not very good as well, so simplified and revised.

Create a function that returns the sorting lambda (the Array.prototype.sort callback that does the actual sorting). That function can receive the key name, the kind of sorting (string (case sensitive or not) or numeric) and the sorting order (ascending/descending). The lambda uses the parameter values (closure) to determine how to sort.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement