0

I need to make a sort by Status and ETA, I've managed to make the sort by Status by can't figure out to make it also by ETA. What I've done so far is only sorting by Status, it should sort by ETA also, but I can't manage to figure out why this solution is not working.

Here is my code:

const data = [
        {
          id: 1,
          name: "Delivery 1",
          amount: 3,
          status: "active",
          eta: 15
        },
        {
          id: 2,
          name: "Delivery 2",
          amount: 5,
          status: "pending"
        },
        {
          id: 3,
          name: "Delivery 3",
          amount: 3,
          status: "active",
          eta: 10
        },
        {
          id: 4,
          name: "Delivery 4",
          amount: 4,
          status: "upcoming"
        },
        {
          id: 5,
          name: "Delivery 5",
          amount: 3,
          status: "active",
          eta: 25
        },
        {
          id: 6,
          name: "Delivery 6",
          amount: 3,
          status: "active",
          eta: 5
        }
      ];

<tbody>
  {searchResults.sort((a, b) => a.eta > b.eta ? 1 : -1 && statusOrdered.indexOf(a.status) - statusOrdered.indexOf(b.status)).map(el => {
    return (
    <tr>
      <td>{el.id}</td>
      <td>{el.name}</td>
      <td>{el.amount}</td>
      <td>{el.eta}</td>
      <td>{el.status}</td>
    </tr> 
    );
  })}
  </tbody>
    </table>
  );
};

3
  • For your input, in your code, what will be your desired output value? Commented Jun 18, 2022 at 9:39
  • Does this answer your question? How to sort an array of objects by multiple fields? Commented Jun 18, 2022 at 9:44
  • it's just a.eta - b.eta || statusOrdered.indexOf(a.status) - statusOrdered.indexOf(b.status) see the duplicate for discussion or other variations. (reverse the calculations to sort by status first) Commented Jun 18, 2022 at 9:45

1 Answer 1

1

Just to explain you how it will look like, consider the following example.

(a.eta - b.eta) || (a.status - b.status)

So you need to use || instead of &&.

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

2 Comments

It's a duplicate, flag to close
It works as expected! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.