Search code examples
javascriptarrayssortingmultiple-conditions

How to sort items in arrays meeting three conditions?


I am trying since several hours to make it work. That is why I finally decided to ask you if it is even possible to achieve this by using one single sort-method.

I have an array of objects with the following type:

{
  seats: number
  area: string
}[]
  1. Now I would like to have all the objects with 5 seats on the top of the array.

  2. Of those the ones that have "garden" as an area should be on the top.

  3. The ones that have more than 5 seats should follow in an ascending order.

  4. The rest should follow in a descending order.

I am very frustrated right now. I did not think that this is that difficult...


Solution

  • Let's say this is the array you have

    const data = [
      { seats: 6, area: 'garden' },
      { seats: 3, area: 'garden' },
      { seats: 5, area: 'patio' },
      { seats: 7, area: 'patio' },
      { seats: 2, area: 'indoor' },
      { seats: 5, area: 'garden' },
      { seats: 4, area: 'patio' },
    ];
    

    you can sort it like this:

    data.sort((a, b) => {
    
      // if one object has five seats, prioritize it
      if (a.seats === 5 && b.seats !== 5) {
        return -1; // a comes first
      } else if (b.seats === 5 && a.seats !== 5) {
        return 1; // b comes first
      } else if (a.seats === b.seats) {
    
        // if they both have the same number of seats, prioritize the 'garden'
        if (a.area === 'garden' && b.area !== 'garden') {
          return -1; // a comes first
        } else if (b.area === 'garden' && a.area !== 'garden') {
          return 1; // b comes first
        } else {
          return 0; // no change in order
        }
    
      // if it's more than 5 seats, sort it by ascending. otherwise, descending.
      } else if (a.seats > 5 && b.seats > 5) {
        return a.seats - b.seats; // ascending order
      } else {
        return b.seats - a.seats; // descending order
      }
    });