-2

Does anyone know how to write an implementation of a function that sorts an array in the following way:

Given the following array(randomly ordered):

["1.2", "1.5.3", "1.5", "1.5.2", "1.4", "1.5.3.2", "1", "1.1", "1.5.3.1", "1.2.1", "1.3", "1.5.1", "2", "2.2", "2.1", "3.1", "3", "3.2.1", "3.2.2", "3.2", "3.3", "4"]

it should result into ->

["1", "1.1", "1.2", "1.2.1", "1.3", "1.4", "1.5", "1.5.1", "1.5.2", "1.5.3", "1.5.3.1", "1.5.3.2", "2", "2.1", "2.2", "3", "3.1", "3.2", "3.2.1", "3.2.2", "3.3", "4"]

I'm currently trying to do it in JavaScript with .sort(), and not really succeeding. Logic in any language would be greatly appreciated.

Heretic Monkey
  • 11,078
  • 7
  • 55
  • 112
Apophis
  • 349
  • 5
  • 12

2 Answers2

-1

.sort actually works fine just by itself here.

const array = ["1.2", "1.5.3", "1.5", "1.5.2", "1.4", "1.5.3.2", "1", "1.1", "1.5.3.1", "1.2.1", "1.3", "1.5.1", "2", "2.2", "2.1", "3.1", "3", "3.2.1", "3.2.2", "3.2", "3.3", "4"]

console.log(
  array.sort()
)
richytong
  • 2,302
  • 9
  • 18
-1
const arr = ["1.2", "1.5.3", "1.5", "1.5.2", "1.4", "1.5.3.2", "1", "1.1", "1.5.3.1", "1.2.1", "1.3", "1.5.1", "2", "2.2", "2.1", "3.1", "3", "3.2.1", "3.2.2", "3.2", "3.3", "4"];
arr.sort();

the result is =

["1", "1.1", "1.2", "1.2.1", "1.3", "1.4", "1.5", "1.5.1", "1.5.2", "1.5.3", "1.5.3.1", "1.5.3.2", "2", "2.1", "2.2", "3", "3.1", "3.2", "3.2.1", "3.2.2", "3.3", "4"]
cigien
  • 55,661
  • 11
  • 60
  • 99