为了账号安全,请及时绑定邮箱和手机立即绑定

Array.sort()比较函数返回undefined

Array.sort()比较函数返回undefined

富国沪深 2019-04-17 10:15:16
我正在尝试排序从最旧到最新的字符串日期数组。我设置了几个比较功能,但控制台说的a是undefined。出了什么问题?//Sort an array of dates in this formatconst dates = ['10','23 Apr 2018','01 Jun 1943','05 Aug 2055','22 Sep 1902''18 Aug 1970','01  Jan 1940','08 Mar 2018','11 Feb 1982','17 Mar 1927',  ]; //remove the data that is not in the correct formatconst cleanedDates = dates.filter(date => date.length === 11); //isolate the day, convert to numberconst getDay = (str) => {   return parseInt(str.slice(0,2));};//create a dictionary of monthsconst monthDict = {   Jan: 1,   Feb: 2,   Mar: 3,   Apr: 4,   May: 5,   Jun: 6,   Jul: 7,   Aug: 8,   Sep: 9,   Oct: 10,   Nov: 11,   Dec: 12};//get the month value via dictionaryconst getMonth = (str) => {   const month = str.slice(3,6);   return monthDict[month];};//get the year, convert to numberconst getYear = (str) => {   return parseInt(str.slice(7));}//comparison helper functions//compare dayconst compareDay = (a,b) => {   if (getDay(a) < getDay(b)) {     return -1;   } else if (getDay(a) === getDay(b)) {     return 0;   }   } else if (getDay(a) > getDay(b)) {     return 1;   }};//compare monthconst compareMonth = (a,b) => {   if (getMonth(a) < getMonth(b)) {     return -1   } else if (getMonth(a) === getMonth(b)) {     compareDay(a,b);   } else if (getMonth(a) > getMonth(b)) {     return 1;   }};//compare yearconst compareYear = (a,b) => {   if (getYear(a) < getYear(b)) {     return -1;   } else if (getYear(a) === getYear(b)) {     compareMonth(a,b);   }   } else if (getYear(a) > getYear(b)) {     return 1   }};//sort arrayconst sortedArray = cleanedDates.sort((a,b) => compareYear(a,b));console.log(sortedArray);
查看完整描述

2 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞


清理日期数组后没有语法错误,请尝试以下操作:


// convert to date

dates.map( el => new Date(el));

// sort it

dates.sort( (a,b) => a>b);


查看完整回答
反对 回复 2019-05-17
  • 2 回答
  • 0 关注
  • 844 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信