-1

I have an Array of Objects (Properties) that I need to sort by multiple criteria, 4 in total. I have managed two of them, but the second and third are giving me issues.

The sorting order has to be:

1st - if a property has a status of "Active", that goes before a property with a status of "Escrow", this one is easy because I can just so alphabetically since "active" goes before "escrow".

2nd - If a property has a property-type of "Multifamily" that goes before the rest (not working)

3rd - If a property has a status of "Land" that goes before the rest (but after Multifamily, not working)

4th - Sort by number of Units, again, this one is easy.

Here is my code so far, I'm using a microlibrary to sort Arrays but the usuall Array.sort logic functions will work here, the library is called thenBy.js:

Not only the "Multifamily" and "Land" sorting is not working, it's also duplicating entries...I'm really not sure how to approach this one.

const filtered_properties = []

filtered_properties.sort(
  firstBy(function(v1, v2) {
    if (v1.status > v2.status) {
      return 1;
    } else if (v1.status < v2.status) {
      return 0;
    }
  })
  // Not working
  .thenBy(function(v1) {
    return (
      v1["property-type"] &&
      v1["property-type"][0].name === "Multifamily"
    );
  })
  // Not working
  .thenBy(function(v1) {
    return (
      v1["property-type"] &&
      v1["property-type"][0].name === "Land"
    );
  })
  .thenBy(function(v1, v2) {
    return v2.units - v1.units;
  })
);
<script src="https://cdn.jsdelivr.net/npm/thenby@1.3.4/thenBy.min.js"></script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Sergi
  • 1,192
  • 3
  • 19
  • 37

1 Answers1

1

Depending on your properties, you could compare with the wanted top string and take the delta of b - a of the comparison and if you need the wanted string at bottom, switch a and b.

The same applies for all other comparisons where an item has to be sorted to top.

array.sort((a, b) =>
    (b.status === 'Active') - (a.status === 'Active') ||
    (b.type === 'Multifamily') - (a.type === 'Multifamily') ||
    (b.status === 'Land') - (a.status === 'Land') ||
    a.units - b.units
);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • That's close but not 100% there. The properties that have a different type that is not "Multifamily" or "Land" just appear in the middle. How can I place those after "Multifamily" and "Land"? – Sergi Jan 10 '22 at 14:24
  • please add a small amount of data to the question. – Nina Scholz Jan 10 '22 at 15:05
  • The above works, it's just that for example, a property has a type of "Office", then it just appears at the same spot instead of at the end, every other type should be after "Multifamily" and "Land". – Sergi Jan 10 '22 at 17:35
  • do you want to sort the same properties by some values (like [this](https://stackoverflow.com/a/65688069/1447675))? – Nina Scholz Jan 10 '22 at 17:40