2

I have an array of strings, which might contain numbers represented as strings.

var data = ['BK1125', '5', '3', '2', '1', '11', '001', 'BK123', 'BK121', '4']

Now, I want to sort it so that final output should be

var data = ['001', '1', '2', '3', '4','5','11','BK121', 'BK123', 'BK1125']

I understand that plain sort() function will not be able to do it. I tried to look at many answers but still didn't get the expected results.

Thanks in advance.

3
  • What prevents data.sort() from handling this? Commented Feb 18, 2015 at 6:22
  • try this data.sort(function(a, b){ return parseInt(a.match(/(\d+)/)[0]) < parseInt(b.match(/(\d+)/)[0]) ? -1 : 1;}) Commented Feb 18, 2015 at 6:36
  • I got this working by using the answers in the duplicated question. Commented Feb 18, 2015 at 11:03

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.