1

I have a mixed array that I need to sort by digit and then by alphabet

var x = ['1','2A','2B','2AA','2','10A','10','11','12A','12B','12']

Desired Output

sortedArray = ['1','2','2A','2B','2AA','10','10A','11','12','12A','12B']

I had tried using lodash but wasn't getting desired result

var x = ['1','2A','2B','2AA','2','10A','10','11','12A','12B','12']

_.sortBy(x);

//lodash result

 ["1", "10", "10A", "11", "12", "12A", "12B", "2", "2A", "2AA", "2B"]
0

2 Answers 2

3

You can use parseInt to get the number part and sort it. If both a and b have the same number, then sort them based their length. If they both have the same length, then sort them alphabetically using localeCompare

let array = ['1','2A','2B','2AA','2','10A','10','11','12A','12B','12'];

array.sort((a, b) => parseInt(a) - parseInt(b) 
                  || a.length - b.length 
                  || a.localeCompare(b));
                  
console.log(array)

Sign up to request clarification or add additional context in comments.

6 Comments

needed 2AA after 2B refer the desired output above
@Snivio what is logic for putting AA after B?
x.sort((a, b) => parseInt(a) - parseInt(b) || a.length - b.length || a.localeCompare(b));
@PranavCBalan Thanks, I have added that. Your answer looks much more extensible.
@adiga : yours would be faster :)
|
2

You can use custom sot function, within custom function split digit and non-digit seperately and sort based on num and if both are equal compare the non-digit part.

const arr = ['1', '2A', '2B', '2AA', '2', '10A', '10', '11', '12A', '12B', '12']

arr.sort((a, b) => {
  // extract digit and non-digit part from string
  let as = a.match(/(\d+)(\D*)/);
  let bs = b.match(/(\d+)(\D*)/);
  // either return digit differennce(for number based sorting)
  // in addition to that check string length(in case digits are same)
  // or compare non-digit part(string comparison)
  return as[1] - bs[1] || a.length - b.length ||as[2].localeCompare(bs[2]);
})

console.log(arr)

2 Comments

needed 2AA after 2B refer the desired output above
@Snivio :compare the string length as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.