I'm trying to implement a custom sort
function. I have these rules:
['B', 'A'] => will become ['A', 'B']
['2', '1'] => will become ['1', '2']
['Down', 'Up'] => will become ['Up', 'Down']
So if there are numbers or strings I want to sort them in ascended order, but if i have the keywords Up/Down
, I want Up
first, then Down
.
Here is what I've tried so far:
let c = [ { pos: 'Down', }, { pos: 'Up', }, ]; c.sort(function (a, b) { console.log(a.pos) // why is this 'Up' and not 'Down'? if (a.pos === 'Down' && b.pos === 'Up') { console.log('enter on 1'); return 1; } else { if (a.pos > b.pos) { console.log('enter on 2'); return 1; } } console.log('enter on 3'); return -1; }); console.log(c); // expected result [{pos: 'Up'}, {'pos': 'Down'}]
I was expecting my code to enter on 1
but it enters on enter on 2
instead. So why if I console.log(a.pos)
I obtain Up
and not Down
?
Thank you for your time!
function mySort(arr) { arr.sort(function (a, b) { a = a.pos; b = b.pos; if (a==='up' && b==='down') return -1; if (b==='up' && a==='down') return 1; if (!(isNaN(a))) return ab; return a.localeCompare(b); }); return arr; } console.log(mySort([{pos:'Down'}, {pos:'Up'}])); console.log(mySort([{pos:'B'},{pos:'X'},{pos:'A'}])); console.log(mySort([{pos:12},{pos:56},{pos:2},{pos:0}]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.