-1

i ve an array which looks like this :

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"}]

i'm sorting thos object by "birthday"

myarray.sort((a, b) => new Date(b.birthday).getTime() - new Date(a.birthday).getTime());

but sometimes , i ve the same birthday value for two objects (birthday is equal) , in that case i want that the sort compares those two objects (not all the objects) with the higher "id" (which have the higher id is prior)

Suggestions ?

2

1 Answer 1

1

You need to add a separate case in the sort function as follows:

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.