Search code examples
javascriptarraysreactjsreact-nativeconditional-operator

Sort array of objects by multiple properties of string type


I am sorting my array in JavaScript based on names after then I am sorting it based in joinDate but somehow it is not checking for joiningDate.

Unfortunately, I can't use an if-else condition - I only want to use ternary operators.

My code is like this:

person.sort(((a, b) => (a.name > b.name)  ? 1 : (a.joinDate > b.joinDate) ? 1 : -1));

It is sorting the names but not sorting the joinDate property

My list look like this:

{
"data": [
     {
         "id": "fdsf",
         "name": "Julie",
         "joinDate": "01/10/2019"

      },
    ]
}

Solution

  • The test should be (assuming your date format is dd/mm/yyyy)

    if (a.name > b.name) return 1;
    if (a.name < b.name) return -1;
    let [a_dd, a_mm, a_yy] = a.joindate.split("/");
    let [b_dd, b_mm, b_yy] = b.joindate.split("/");
    if (a_yy !== b_yy) return a_yy - b_yy;
    if (a_mm !== b_mm) return a_mm - b_mm;
    if (a_dd !== b_dd) return a_dd - b_dd;
    return 0;