首页 > 其他分享 >js sort array by date string All In One

js sort array by date string All In One

时间:2022-11-30 02:33:13浏览次数:71  
标签:sort 01 return title markdown date array

js sort array by date string All In One

bug


const log = console.log;

const arr = [
  { title: 'markdown title', date: '2021-01-01' },
  { title: 'markdown title', date: '2022-11-01' },
  { title: 'markdown title', date: '2022-11-30' },
  { title: 'markdown title', date: '2022-12-01' },
  { title: 'markdown title', date: '2022-12-31' },
  { title: '✅ markdown title', date: '2012-01-01' }
];

// date string sort bug ❌
const sorted = arr.sort(({ date: a }, { date: b }) => {
  if (a < b) {
    return 1;
  } else if (a > b) {
    return -1;
  } else {
    return 0;
  }
});


image

solution


const log = console.log;

const arr = [
  { title: 'markdown title', date: '2021-01-01' },
  { title: 'markdown title', date: '2022-11-01' },
  { title: 'markdown title', date: '2022-11-30' },
  { title: 'markdown title', date: '2022-12-01' },
  { title: 'markdown title', date: '2022-12-31' },
  { title: '✅ markdown title', date: '2012-01-01' }
];

// const meta = arr.map(obj => obj.metadata);
// log(`meta =`, meta);
// return arr;
// const sorted = arr.sort(({ date: a }, { date: b }) => {
//   // 升序排序,最旧的在最前面 ❌
//   if (a < b) {
//     return -1;
//   } else if (a > b) {
//     return 1;
//   } else {
//     return 0;
//   }
// });
const sorted = arr.sort(({ date: a }, { date: b }) => {
  // 降序排序,最新的在最前面 ✅
  if (a < b) {
    return 1;
  } else if (a > b) {
    return -1;
  } else {
    return 0;
  }
});
log(`sorted =`, sorted.map(obj => obj.metadata));
return sorted;

image

Date.prototype.setHours()

//

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours

refs

String => Date

https://masteringjs.io/tutorials/fundamentals/sort-by-date

https://github.com/mastering-js/masteringjs.io

https://www.delftstack.com/howto/javascript/sort-by-date-javascript/

https://thewebdev.info/2022/01/23/how-to-sort-a-date-string-array-with-javascript/


Flag Counter

©xgqfrms 2012-2020

www.cnblogs.com/anonymous007 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️anonymous007, 禁止转载

标签:sort,01,return,title,markdown,date,array
From: https://www.cnblogs.com/anonymous-ufo/p/16937268.html

相关文章