Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Sorting js array containing number as string

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!