1

js数组排序整理

 2 years ago
source link: https://segmentfault.com/a/1190000041001875
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

js数组排序整理

(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”]

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK