Home > other >  Algorithm to sort an array in javascript
Algorithm to sort an array in javascript

Time:11-03

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

CodePudding user response:

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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related