(1) 數值排序 | 上升 [⇣⁰₉]
const arr = [40, 100, 1, 5, 25, 10];
arr.sort(function(a, b){
return a-b;
});
之前:[40,100,1,5,25,10]
之後:[1,5,10,25,40,100]
(2) 數值排序 | 降序[⇣⁹₀]
const arr = [40, 100, 1, 5, 25, 10];
arr.sort(function(a, b){
return b-a;
});
之前:[40,100,1,5,25,10]
之後:[100,40,25,10,5,1]
(3) 字母排序 | 上升✷ [⇣ᴬᴢ]
const arr = ["Blue", "Orange", "Aqua", "Marine"];
arr.sort()
之前:["Blue", "Orange", "Aqua", "Marine"]
之後:['Aqua', 'Blue', 'Marine', 'Orange']
(4) 字母排序 | 降序✷ [⇣ᶻᴀ]
const arr = ["Blue", "Orange", "Aqua", "Marine"];
arr.sort().reverse();
之前:["Blue", "Orange", "Aqua", "Marine"]
之後:['Orange', 'Marine', 'Blue', 'Aqua']
(5) 日期排序 | 上升 [▲]
const arr = ["2015-03-25", "2015-02-01", "2015-01-03", "2015-02-02"];
arr.sort(function(a, b){
return new Date(a)-new Date(b);
});
之前:[“2015-03-25”、”2015-02-01”、”2015-01-03”、”2015-02-02”]
之後:[“2015–01–03”、”2015–02–01”、”2015–02–02”、”2015–03–25”]
(6) 日期排序 | 降序 [▼]
const arr = ["2015-03-25", "2015-02-01", "2015-01-03", "2015-02-02"];
arr.sort(function(a, b){
return new Date(b)-new Date(a);
});
之前:[“2015-03-25”、”2015-02-01”、”2015-01-03”、”2015-02-02”]
之後:[“2015–03–25”、”2015–02–02”、”2015–02–01”、”2015–01–03”]