0

I have the following array. How can I sort it properly? I tried the following:

var array = ["1000:2", "101:234", "102", "101:11", "11", "12"];
array.sort(function(a, b) {
  return  a.localeCompare(b)
})
console.log(array)

But its not giving the correct output. After sorting it should produce: 11, 12, 101:11, 101:234, 102, 1000:2. Thank you in advance!

Nihar
  • 333
  • 1
  • 6
  • 18

1 Answers1

2

You can call parseInt on the arguments, which will take only the initial numeric part of the argument (dropping the : and anything past it, if it exists):

var array = ["1000:2", "101:234", "102", "11", "12"];
array.sort((a, b) => parseInt(a) - parseInt(b))
console.log(array)

If you were intending to treat the . like a decimal, then replace the : with a ., then subtract to find the difference:

var array = ["1000:2", "101:234", "102", "11", "12"];
array.sort((a, b) => a.replace(':', '.') - b.replace(':', '.'))
console.log(array)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320