Javascript:用第一个属性对对象数组进行排序,当相等时与另一个排序
Javascript: sort an array of objects with a first attribute , and when equal sort with another
我有一个数组,如下所示:
let myarray =
[{id:1 , name: "mark" , birthday: "1990-08-18"},
{id:2 , name: "fred" , birthday: "1990-08-17"},
{id:3 , name: "franck" , birthday: "1990-08-16"},
{id:4 , name: "mike" , birthday: "1990-08-15"},
{id:5 , name: "jean" , birthday: "1990-08-17"}]
我正在按“生日”对这些对象进行排序
myarray.sort((a, b) => new Date(b.birthday).getTime() - new Date(a.birthday).getTime());
但有时,两个对象的生日值相同(生日相同),
在那种情况下我希望排序将这两个对象(不是所有对象)与更高的进行比较“id"(id高的优先)
建议 ?
需要在sort
函数中单独添加一个case如下:
let myarray = [
{id:1 , name: "mark" , birthday: "1990-08-18"},
{id:2 , name: "fred" , birthday: "1990-08-17"},
{id:3 , name: "franck" , birthday: "1990-08-16"},
{id:4 , name: "mike" , birthday: "1990-08-15"},
{id:5 , name: "jean" , birthday: "1990-08-17"}
]
myarray.sort((a, b) => {
let dif = new Date(b.birthday).getTime() - new Date(a.birthday).getTime();
if(dif != 0) return dif;
else return b.id - a.id;
});
console.log(myarray);
我有一个数组,如下所示:
let myarray =
[{id:1 , name: "mark" , birthday: "1990-08-18"},
{id:2 , name: "fred" , birthday: "1990-08-17"},
{id:3 , name: "franck" , birthday: "1990-08-16"},
{id:4 , name: "mike" , birthday: "1990-08-15"},
{id:5 , name: "jean" , birthday: "1990-08-17"}]
我正在按“生日”对这些对象进行排序
myarray.sort((a, b) => new Date(b.birthday).getTime() - new Date(a.birthday).getTime());
但有时,两个对象的生日值相同(生日相同), 在那种情况下我希望排序将这两个对象(不是所有对象)与更高的进行比较“id"(id高的优先)
建议 ?
需要在sort
函数中单独添加一个case如下:
let myarray = [
{id:1 , name: "mark" , birthday: "1990-08-18"},
{id:2 , name: "fred" , birthday: "1990-08-17"},
{id:3 , name: "franck" , birthday: "1990-08-16"},
{id:4 , name: "mike" , birthday: "1990-08-15"},
{id:5 , name: "jean" , birthday: "1990-08-17"}
]
myarray.sort((a, b) => {
let dif = new Date(b.birthday).getTime() - new Date(a.birthday).getTime();
if(dif != 0) return dif;
else return b.id - a.id;
});
console.log(myarray);