0

I've implement this sort:

<tbody>
  {results.sort((a, b) => a.status > b.status ? 1 : -1).map(el => {
    return (
    <tr>
      <td>{el.id}</td>
      <td>{el.amount}</td>
      <td>{el.time}</td>
      <td>{el.status}</td>
     
    </tr> 
    );
  })}
  </tbody>

So now I have them sorted by status as follows: active, updated, waiting. The problem is that I want them sorted by active, waiting, updated. How can I achieve this?

This is my array of objects:

 const data = [
        {
          id: 1,
          title: "Order 1",
          amount: 3,
          status: "active"
        },
        {
          id: 2,
          title: "Order 2",
          amount: 5,
          status: "waiting"
        },
        {
          id: 3,
          title: "Order 3",
          amount: 4,
          status: "updated"
        },
        {
          id: 4,
          title: "Order 4",
          amount: 3,
          status: "active"
        }
      ];
1

2 Answers 2

2

You can use indexOf to an ordered array, with this approach:

const data = [{
    id: 1,
    title: "Order 1",
    amount: 3,
    status: "active"
  },
  {
    id: 2,
    title: "Order 2",
    amount: 5,
    status: "waiting"
  },
  {
    id: 3,
    title: "Order 3",
    amount: 4,
    status: "updated"
  },
  {
    id: 4,
    title: "Order 4",
    amount: 3,
    status: "active"
  }
];

const statusOrdered = ['active', 'waiting', 'updated']

data.sort((a, b) => statusOrdered.indexOf(a.status) - statusOrdered.indexOf(b.status));

console.log(data)

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

Comments

1

Try something like this for your sorting function.

(a,b) => {
    let ranking = {
        active:1,
        waiting:2,
        updated:3,
    }
    return ranking[a.status] - ranking[b.status]
}

Comments

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.