简体   繁体   English

javascript中不同对象数组的一个排序函数

[英]one sort function for different arrays of object in javascript

I want to sort both the array with one comman sort function that can sort by date. 我想用一个可以按日期排序的comman sort函数对数组进行排序。

videos = [
    {publishDate: new Date("2016-07-20T07:45:00Z").toISOString()}, 
    {publishDate: new Date("2016-07-27T07:45:00Z").toISOString()}, 
    {publishDate: new Date("2016-07-23T07:45:00Z").toISOString()}
];

persons = [
    {dob: new Date("2016-07-10T07:45:00Z").toISOString()}, 
    {dob: new Date("2016-07-08T07:45:00Z").toISOString()}, 
    {dob: new Date("2016-07-11T07:45:00Z").toISOString()}
];

I can sort with this function byDate() 我可以用这个函数排序byDate()

function byDate(v1, v2) {
    return v1.p > v2.p ? 1 : -1;
}

videos.sort(byDate);

but when I call this function with persons[] array, this gives error because v1.p is not present in persons[] array. 但是当我用person []数组调用这个函数时,这会产生错误,因为在[]数组中没有v1.p。

So, I need one sort function that can sort different arrays of objects. 所以,我需要一个可以对不同对象数组进行排序的排序函数。

You need to specify the key, you like to sort with. 你需要指定密钥,你喜欢排序。 This solution takes the key and returns a function for sorting. 此解决方案获取密钥并返回一个用于排序的函数。

 function byDate(key) { return function (a, b) { return a[key].localeCompare(b[key]); }; } var videos = [{ publishDate: new Date("2016-07-20T07:45:00Z").toISOString() }, { publishDate: new Date("2016-07-27T07:45:00Z").toISOString() }, { publishDate: new Date("2016-07-23T07:45:00Z").toISOString() }], persons = [{ dob: new Date("2016-07-10T07:45:00Z").toISOString() }, { dob: new Date("2016-07-08T07:45:00Z").toISOString() }, { dob: new Date("2016-07-11T07:45:00Z").toISOString() }]; console.log(videos.sort(byDate('publishDate'))); console.log(persons.sort(byDate('dob'))); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

simply try, 试试吧,

  videos = [ {publishDate: new Date("2016-07-20T07:45:00Z").toISOString()}, {publishDate: new Date("2016-07-27T07:45:00Z").toISOString()}, {publishDate: new Date("2016-07-23T07:45:00Z").toISOString()} ]; persons = [ {dob: new Date("2016-07-10T07:45:00Z").toISOString()}, {dob: new Date("2016-07-08T07:45:00Z").toISOString()}, {dob: new Date("2016-07-11T07:45:00Z").toISOString()} ]; function byDate(v1, v2) { return Object.values(v1) > Object.values(v2) ? 1 : -1; } console.log(videos.sort(byDate)); console.log(persons.sort(byDate)); 

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

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