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 28 29 30 31 32 33 34 35 36 37
| const d = [2, 10, 1, -1] const arr = [ { id: 1, title: 'Learn Vue' }, { id: 3, title: 'Learn React' }, { id: 2, title: 'Learn Angular' }, ]
d.sort(buildSorter()) arr.sort(buildSorter('id'))
console.log(d) console.log(arr)
[-1, 1, 2, 10]
[ { id: 1, title: 'Learn Vue' }, { id: 2, title: 'Learn Angular' }, { id: 3, title: 'Learn React' }, ]
function buildSorter(on, SORT = 'ASC') { SORT = SORT.toUpperCase()
const sign = SORT === 'ASC' ? 1 : -1
if ( on ) { return (a, b) => sign * (a[on] - b[on]) }else { return (a, b) => sign * (a - b) } }
|