0

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

1
  • Seems like your input uses BinRange while your code sorts by AgeBin Commented Aug 8, 2022 at 10:22

2 Answers 2

1
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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.