简体   繁体   中英

How can i fix the method sort to work properly for my task?

I am trying to sort dates by ascending, but it doesn't sort quite right.

I have tried several different ways to do it. But it keeps on having the same problem.

const arr = [
  { date: "01.01.2017", dayOfWeek: "Tuesday" },
  { date: "01.01.2016", dayOfWeek: "Saturday" },
  { date: "01.01.2002", dayOfWeek: "Wednesday" },
  { date: "01.01.2003", dayOfWeek: "Wednesday" }
];
const sort = arr
  .sort((a, b) =>
    new Date(a.date).getTime > new Date(b.date).getTime ? 1 : -1
  )
  .map(function(m) {
    console.log(m.date, m.dayOfWeek);
  });

What I expect:

01.01.2002 Wednesday

01.01.2003 Wednesday

16 01.01.2016 Saturday

16 01.01.2017 Tuesday

but the output I get is this:

01.01.2003 Wednesday

01.01.2002 Wednesday

16 01.01.2016 Saturday

16 01.01.2017 Tuesday

Your code was almost right; you didn't call the function getTime of new Date .

Note: The best way to sort numbers and dates is by using subtraction.

Note 2: Using console.log with Array.map will end up with an array of undefined .

 const arr = [ { date: "01.01.2017", dayOfWeek: "Tuesday" }, { date: "01.01.2016", dayOfWeek: "Saturday" }, { date: "01.01.2002", dayOfWeek: "Wednesday" }, { date: "01.01.2003", dayOfWeek: "Wednesday" } ].sort( (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime() ).forEach(m => { console.log(m.date, m.dayOfWeek); }); 

getTime是一个函数,您需要执行它才能实际比较值:

new Date(a.date).getTime() > new Date(b.date).getTime()? 1 :-1

you can also try it without getTime() as both are of type Date so they can be compared directly.

  const sort = arr
    .sort( (a, b) =>
      new Date(a.date) > new Date(b.date) ? 1 : -1
    )
    .map(function(m) {
      console.log(m.date, m.dayOfWeek);
    });

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM