forked from eggheadio-github/stack-overflow-copy-paste
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort-objects-array.js
More file actions
27 lines (26 loc) · 795 Bytes
/
Copy pathsort-objects-array.js
File metadata and controls
27 lines (26 loc) · 795 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
export default sortObjectsArray
/**
* Original Source: http://stackoverflow.com/a/4760279/3142309
*
* This method returns a function that can be passed into Array.sort to sort an array of objects by a given property.
* Prepending "-" to the property argument sorts the array in descending order.
*
* @param {String} property - The property to sort by
* @return {Function} - A function that can be passed into Array.sort
*/
function sortObjectsArray(property) {
let sortOrder = 1
if (property[0] === '-') {
sortOrder = -1
property = property.substr(1)
}
return function compareFunction(a, b) {
let result = 0
if (a[property] < b[property]) {
result = -1
} else if (a[property] > b[property]) {
result = 1
}
return result * sortOrder
}
}