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

Christian
  • 53
  • 1
  • 8
  • For your input, in your code, what will be your desired output value? – DanteDX Jun 18 '22 at 09:39
  • Does this answer your question? [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – pilchard Jun 18 '22 at 09:44
  • it's just `a.eta - b.eta || statusOrdered.indexOf(a.status) - statusOrdered.indexOf(b.status)` see the [duplicate](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) for discussion or other variations. (reverse the calculations to sort by `status` first) – pilchard Jun 18 '22 at 09:45

1 Answers1

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 &&.

Rilla
  • 505
  • 4
  • 16
Maradox
  • 620
  • 2
  • 13