Home > Back-end >  Sort array of custom string in JavaScript
Sort array of custom string in JavaScript

Time:08-05

using array sort BinRange is not sorted expected and also. Using Loadash methods also not able to get the result

Loadash:
loadash.orderBy(resData, AgeBin, 'asc'); loadash.sortBy(resData, [function(o) { return o.AgeBin; }]);

Input:

[
    {
        'BinRange': '100-110',
    },
    {
        'BinRange': '110-120',
    },
    {
        'BinRange': '120-130',
    },
    {
        'BinRange': '70-80',
    },
    {
        'BinRange': '80-90',
    },
    {
        'BinRange': '90-100',
    },
    {
        'BinRange': '>150',
    },
];

Expected output:

[
    {
        'BinRange': '70-80',
    },
    {
        'BinRange': '80-90',
    },
    {
        'BinRange': '90-100',
    },
    {
        'BinRange': '100-110',
    },
    {
        'BinRange': '110-120',
    },
    {
        'BinRange': '120-130',
    },
    {
        'BinRange': '>150',
    },
];

Please suggest a way to do it

CodePudding user response:

You could sort based on the number at the end of the BinRange string. Use /\d $/ to get that number

const input = [{BinRange:"100-110"},{BinRange:"110-120"},{BinRange:"120-130"},{BinRange:"70-80"},{BinRange:"80-90"},{BinRange:"90-100"},{BinRange:">150"}];

input.sort((a,b) => a.BinRange.match(/\d $/g)[0] - b.BinRange.match(/\d $/g)[0] )

console.log(input)

CodePudding user response:

function getProperStartRange(range) {
  if (range["BinRange"][0] === ">") {
    return Number.parseInt(range["BinRange"].slice(1))   1;
  } else if (range["BinRange"][0] === "<") {
    return Number.parseInt(range["BinRange"].slice(1)) - 1;
  } else {
    return Number.parseInt(range["BinRange"].split("-")[0]);
  }
}

function sortBinRange(array) {
  array.sort((a, b) => {
    const rangeA = getProperStartRange(a);
    const rangeB = getProperStartRange(b);
    return rangeA - rangeB;
  });
  return array;
}
  • Related