-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 ?

firasKoubaa
  • 6,439
  • 25
  • 79
  • 148
  • [Javascript sort function. Sort by First then by Second](https://stackoverflow.com/questions/9175268/javascript-sort-function-sort-by-first-then-by-second/9175302) – Nikita Madeev Aug 18 '20 at 11:02
  • 1
    btw, with [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) dates, you could sort with [`String#localeCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare). – Nina Scholz Aug 18 '20 at 11:06

1 Answers1

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);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48