简体   繁体   English

使用自定义日期格式对对象进行排序

[英]Sort object with custom date format

Help please me with sorting. 帮助我排序。 I have to sort object with custom string date 我必须使用自定义字符串日期对对象进行排序

var object = [{
  name: "something",
  date: "23.12.2016"
},
{
  name: "something2",
  date: "19.12.2016"
}]

how sort object like this? 这样的对象如何排序? I already tried with sort function return new Date(a.date) - new Date(b.date); 我已经尝试过使用sort函数return new Date(a.date) - new Date(b.date); but had nothing it doesn't work Thanks ! 但是什么也没有用,谢谢!

You could split the date and rearrange it as iso date and sort by string with localeCompare . 您可以分割日期并将其重新排列为iso日期,然后使用localeCompare按字符串排序。

 var object = [{ name: "something", date: "23.12.2016" }, { name: "something2", date: "19.12.2016" }]; object.sort(function (a, b) { var aa = a.date.split('.'), bb = b.date.split('.'); return [aa[2], aa[1], aa[0]].join('-').localeCompare([bb[2], bb[1], bb[0]].join('-')); }); console.log(object); 

You could use as well String#replace for reordering the string. 您也可以使用String#replace重新排序字符串。

 var object = [{ name: "something", date: "23.12.2016" }, { name: "something2", date: "19.12.2016" }]; object.sort(function (a, b) { var aa = a.date.replace(/(..).(..).(....)/, '$3-$2-$1'), bb = b.date.replace(/(..).(..).(....)/, '$3-$2-$1'); return aa.localeCompare(bb); }); console.log(object); 

The solution using Date.parse() and String.prototype.replace() functions(to sort by timestamps ): 使用Date.parse()String.prototype.replace()函数的解决方案Date.parse()时间戳排序):

 var date_objects = [{ name: "something", date: "23.12.2016" }, { name: "something2", date: "19.12.2016" }]; date_objects.sort(function(a,b){ return Date.parse(a.date.replace(/^(\\d{2})\\.(\\d{2})\\.(\\d{4})$/, '$3-$2-$1')) - Date.parse(b.date.replace(/^(\\d{2})\\.(\\d{2})\\.(\\d{4})$/, '$3-$2-$1')) }); console.log(date_objects); 

Out of curiosity, I tried a variation about Nina Scholz's answer , maybe it's faster, maybe not. 出于好奇,我尝试对Nina Scholz的答案进行一些修改 ,也许更快,也许没有。 I find reformatting the date quite obvious, but it's also time-consuming. 我发现重新格式化日期很明显,但这也很耗时。 In my version the duplicate indices are probably a problem, but as you stated that the format is zero-padded , this will work: 在我的版本中,重复索引可能是一个问题,但是正如您所说的,格式为零填充 ,这将起作用:

 var object = [{ name: "something", date: "23.12.2016" }, { name: "something2", date: "19.12.2016" }]; object.sort(function (a, b) { return (a.date[6] - b.date[6]) || (a.date[7] - b.date[7]) || (a.date[8] - b.date[8]) || (a.date[9] - b.date[9]) || (a.date[3] - b.date[3]) || (a.date[4] - b.date[4]) || (a.date[0] - b.date[0]) || (a.date[1] - b.date[1]); }); console.log(object); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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