Sorting an array in ascending order for [$250,000 - $1000,000, $75,000 - $250,000, >$1000,000]

sanvi
Tera Expert

Hi All,

 

How to sort an array consisting of values [$250,000 - $1000,000, $75,000 - $250,000, >$1000,000]in ascending order??

The value should look something like  [$75,000 - $250,000, $250,000 - $1000,000, >$1000,000].

 

Tried using sort() not working also tried using orderBy that does not seem to be working as well.

 

Any help would be appreciated.

 

2 REPLIES 2

Astik Thombare
Tera Sage

Hi @sanvi ,

 

Please try below Code 

 

function sortPriceRanges(arr) {
  return arr.sort(function(a, b) {
    // Extract numeric parts using regular expression
    var matchA = a.match(/(\d+)(?:,000)? -/) || [];
    var matchB = b.match(/(\d+)(?:,000)? -/) || [];
    var minA = parseInt(matchA[1], 10) || Infinity;
    var maxA = parseInt(matchA[2], 10) || Infinity;
    var minB = parseInt(matchB[1], 10) || Infinity;
    var maxB = parseInt(matchB[2], 10) || Infinity;

    // Comparison logic for ascending order
    if (minA < minB) return -1;
    if (minA > minB) return 1;
    return maxA - maxB;  // Sort by upper bound if lower bounds are equal
  });
}

var prices = ["$250,000 - $1,000,000", "$75,000 - $250,000", ">$1,000,000"];
var sortedPrices = sortPriceRanges(prices);
gs.info(sortedPrices); // Output: ["$75,000 - $250,000", "$250,000 - $1,000,000", ">$1,000,000"]

 

 

   If my reply helped with your issue please mark helpful 👍 and correct ✔️ if your issue is resolved.

 

                         By doing so you help other community members find resolved questions which may relate to an issue they're having

 

 

Thanks,

 

Astik

Hi @sanvi ,

 

     If my reply helped with your issue please mark helpful 👍 and correct ✔️ if your issue is resolved.

 

                         By doing so you help other community members find resolved questions which may relate to an issue they're having

 

 

Thanks,

Astik