I have a js array like this
[
{ id: '111111', wbs: '1'},
{
id: '22222222222',wbs: '1.2.1'},
{ id: '3333333333', wbs: '10'},
{ id: '4444444444', wbs: '2.1.1.1.1'},
{ id: '55555555555', wbs: '6'}
]
I want to sort it like below
[
{ id: '111111', wbs: '1'},
{
id: '22222222222',wbs: '1.2.1'},
{ id: '4444444444', wbs: '2.1.1.1.1'},
{ id: '55555555555', wbs: '6'}
{ id: '3333333333', wbs: '10'},
]
I have tried to use
arr.sort(function (a, b) {
return a.wbs - b.wbs;
});
and
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
console.log(newWBS.sort(collator.compare));
but both do not give me the desired result. Need help on it. Thank you
const data = [
{ id: '111111', wbs: '1'},
{ id: '22222222222',wbs: '1.2.1'},
{ id: '3333333333', wbs: '10'},
{ id: '4444444444', wbs: '2.1.1.1.1'},
{ id: '55555555555', wbs: '6'}
];
// This function changes 2.5.7.9.3 to 2.5793, etc
function fixNumber(num) {
const n = num.split(".");
n[0] = `${n[0]}.`;
return Number(n.length > 1 ? n.join("") : n[0]);
}
// sort the list
data.sort(
(x, y) => fixNumber(x.wbs) - fixNumber(y.wbs)
)
console.log(data);