-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,687
  • 7
  • 53
  • 122
Apophis
  • 433
  • 1
  • 6
  • 14

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,387
  • 1
  • 10
  • 21
-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
  • 57,834
  • 11
  • 73
  • 112