sortby/index.js

32 lines
775 B
JavaScript
Raw Permalink Normal View History

2023-09-29 00:15:29 -04:00
const sortby = (...properties) => (a, b) => {
2023-09-28 23:12:49 -04:00
// 'base' treat accent as there base character
2023-09-28 22:53:58 -04:00
const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' })
2023-09-11 10:31:30 -04:00
// if items is {prop1:value1, prop2:value2}
// then sort(['prop1', 'desc', 'prop2'])
// will sort by prop1 desc and prop2
2023-09-28 22:51:48 -04:00
for (let i = 0; i < properties.length; i++) {
const property = properties[i]
2023-09-11 10:31:30 -04:00
let order = -1
2023-09-29 00:09:11 -04:00
if (i + 1 < properties.length) {
const next = properties[i + 1]
if (next === 'desc') {
order = 1
i++
} else if (next === 'asc') {
i++
}
2023-09-11 10:31:30 -04:00
}
const compare = collator.compare(a[property], b[property])
2023-09-19 12:10:17 -04:00
if (compare < 0) return order
2023-09-19 16:26:37 -04:00
if (compare > 0) return -order
2023-09-11 10:31:30 -04:00
}
return 0
}
export { sortby }