How To Sort Data Which Mix Text And Number?
I have a data which will show as the table and using orderBy(lodash) to sort data but it's not working as I want. Now, I code as const data = orderBy(realData, ['name'], ['asc'])
Solution 1:
You can use string#localeCompare
callback while sorting an array. To numerically sort the array use numeric
property.
let data = [{name: 'A1'},{name: 'A100'},{name:'A2'},{name: 'A21'},{name:'A22'},{name:'A3'},{name:'B10'},{name: 'B32'}];
data.sort((a,b) => a.name.localeCompare(b.name, undefined, {numeric: true}));
console.log(data);
.as-console-wrapper {max-height: 100%!important; top: 0;}
Solution 2:
An easy to understand way is like this:
data.sort((a, b) => {
const listA = a.name.trim().split('');
const listB = b.name.trim().split('');
const categoryA = listA.splice(0, 1);
const categoryB = listB.splice(0, 1);
const numberA = listA.join('');
const numberB = listB.join('');
if (categoryA > categoryB) return1;
if (categoryA < categoryB) return -1;
return numberA - numberB;
});
Post a Comment for "How To Sort Data Which Mix Text And Number?"