我想知道如何根据包含数字字符串和普通字符串的字段进行移位。
所以,如果数字字符串值然后移到数组末尾,其余部分保持不变
Tried
const sortData = arrobj.sort((a: any, b: any) => {
const sortA = a.cn;
const sortB = b.cn;
if(!isNaN(sortA)) {
return -1;
}
if(!isNaN(sortB)) {
return 1;
}
return sortA.localeCompare(sortB);
});
console.log("sortData", sortData);
var arrobj=[
{cn: '99'}
{cn: 'SG'},
{cn: 'IN'}
]
expecteded output
[
{cn: 'SG'},
{cn: 'IN'},
{cn: '99'}
]
嗯...我认为你只需要在 if 中添加额外的条件...
const arrobj =
[
{cn: '99'},
{cn: 'SG'},
{cn: 'IN'},
];
const sortData = arrobj.sort
(
( $1, $2 ) =>
{
const $1first = -1;
const $2first = 1;
if ( isNaN( parseFloat($1.cn) ) && ! isNaN( parseFloat($2.cn) ) )
{
// Only $1.cn is non-numeric. So, $2.cn is numeric.
return $2first;
}
if ( isNaN( parseFloat($2.cn) ) && ! isNaN( parseFloat($1.cn) ) )
{
// Only $2.cn is non-numeric. So, $1.cn is numeric.
return $1first;
}
// Everything else is sorted by this:
return String($1.cn).localeCompare($2.cn);
}
);
console.log("sortData =", sortData);