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

157
Views
Algorithm to sort an array in javascript

I am having difficulty figuring out a solution.

I have an array similar to this.

// Original array 
const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"]; 

// The sorted array needs to be like this. 
sorted_array = ["1", "1A", "01A", "2", "02B", "03B", "10"]; 

I have tried writing a custom sort function like this but I am unable to find a solution. I appreciate any help.

 const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"];

 const sorted_array = orig_array.sort((a, b) => {
  if (a - b) {
   return a - b;
  }
 if (a.localeCompare(b) === -1) {
  return a.length - b.length;
 } else {
 return 1;
}
});
console.log(sorted_array);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can first apply parseInt to both strings to get the first numeric parts and subtract them. If the numeric parts are equal, then subtract the lengths.

const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"]; 
console.log(orig_array.sort((a,b)=>parseInt(a)-parseInt(b)||a.length-b.length));

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!