JS—按日期对对象或数组进行排序,sort使用总结

2,105 阅读1分钟

按数字大小排序

按升序对数组中的数字进行排序;按降序对数组中的数字进行排序

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});    // 按升序对数组中的数字进行排序
// 数组中的第一项 (points[0]) 现在是最低值

points.sort(function(a, b){return a-b});    // 按降序对数组中的数字进行排序

按字母顺序排序

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();//升序
fruits.reverse();//降序

按日期递增排序

arr.sort((a, b) => a.date.localeCompare(b.date) || a.time.localeCompare(b.time));

const arr = [
  {id: 1, value : "value1", date: "2018-08-08", time: "15:27:17"},
  {id: 2, value : "value2", date: "2018-08-09", time: "12:27:17"},
  {id: 3, value : "value3", date: "2018-08-10", time: "17:27:17"},
  {id: 4, value : "value4", date: "2018-08-10", time: "01:27:17"},
  {id: 5, value : "value5", date: "2018-08-10", time: "09:27:17"},
  {id: 6, value : "value6", date: "2018-08-10", time: "23:27:17"},
  {id: 7, value : "value7", date: "2018-08-10", time: "16:27:17"},
  {id: 8, value : "value8", date: "2018-08-11", time: "10:27:17"}
];
arr.sort((a, b) => a.date.localeCompare(b.date) ||  a.time.localeCompare(b.time)); 
console.log(arr);

image.png

按日期递增排序

arr.sort((a, b) => b.date.localeCompare(a.date) ||  b.time.localeCompare(a.time)); 
console.log(arr);

image.png