skip to Main Content

I want sort by status [‘ready’,’pending’,’in_progress’,’done’]

The list should display

  • data 1 -ready
  • data 2 -ready
  • data 10 -pending
  • data 5 -in_progress
  • data 3 -done

2

Answers


  1. assuming that you using json as data structure for your data:

    var statusArr = ['ready','pending','in_progress','done']
    var dataArr = [{data:"aa",status:"in_progress"},{data:"bb",status:"pending"},{data:"cc",status:"done"},{data:"dd",status:"ready"}]
    
    
    dataArr.sort((a, b) => statusArr.indexOf(a.status) - statusArr.indexOf(b.status));
    
    console.log(dataArr)
    

    this will result:

    [
      { data: 'dd', status: 'ready' },
      { data: 'bb', status: 'pending' },
      { data: 'aa', status: 'in_progress' },
      { data: 'cc', status: 'done' }
    ]
    
    Login or Signup to reply.
  2. You should create a JS objects using reduce() which allows for quick lookups in constant time O(1) which holds the priority or sort position assigned to a value.

    Then using that object you can easily lookup the sort position and sort accordingly. The overall runtime of the algorithm is O(n). If you use something like indexOf() the runtime will be O(n²) since indexOf() does a linear search.

    I am using the relatively new toSorted() instead of the older sort() method here since toSorted() returns a new array and is therefore the immutable option, which should generally be preferred. Browser support is not especially good as of now, so by reason of that you might need to fallback to sort().

    const statuses = ['ready', 'pending', 'in_progress', 'done'];
    const unsorted = [{
      data: "aa",
      status: "in_progress"
    }, {
      data: "bb",
      status: "pending"
    }, {
      data: "cc",
      status: "done"
    }, {
      data: "dd",
      status: "ready"
    }]
    
    const statusPriorities = statuses.reduce((all, cur, i) => (all[cur] = i, all), {});
    
    
    // use sort() to manipulate the original array (mutable variant)
    // we use the immutable variant here
    const sorted = unsorted.toSorted((a, b) => statuses[a.status] - statuses[b.status]);
    console.log(sorted);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search