[英]Sort array of custom string in JavaScript
using array sort BinRange is not sorted expected and also.使用数组排序 BinRange 也不是预期的排序。 Using Loadash methods also not able to get the result
使用 Loadash 方法也无法得到结果
Loadash:加载:
loadash.orderBy(resData, AgeBin, 'asc'); loadash.orderBy(resData, AgeBin, 'asc'); loadash.sortBy(resData, [function(o) { return o.AgeBin; }]);
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:预期 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请提出一种方法来做到这一点
You could sort based on the number at the end of the BinRange
string.您可以根据
BinRange
字符串末尾的数字进行排序。 Use /\d+$/
to get that number使用
/\d+$/
获取该数字
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)
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.