-4

I have a couple of strings in an array.

For example:

[
    "path/to/file",
    "path",
    "path/to/",
    "path2/to/file",
    "path2/to/file",
    "path2/to"
]

etc...

The thing that i would like to achieve is to sort the array based on the the count of the slash. So the less count slashes on top.

So it would be like:

[
    "path",
    "path/to/",
    "path2/to",
    "path/to/file",
    "path2/to/file",
    "path2/to/file"
]
Ivar
  • 6,138
  • 12
  • 49
  • 61
user2445977
  • 1
  • 1
  • 2
  • 6
  • 1
    Possible duplicate of [How to sort an array based on the length of each element?](https://stackoverflow.com/questions/10630766/how-to-sort-an-array-based-on-the-length-of-each-element) – sertsedat Sep 07 '18 at 20:41

2 Answers2

3
strings.sort(function(a, b) {
    return a.split("/").length - b.split("/").length;
});
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
dustytrash
  • 1,568
  • 1
  • 10
  • 17
2

You will need to use the custom function of Array sort method like this

var array_strings = ["path","path/to/","path/to/file"];
array_strings.sort(function(a, b){
  var a_length = a.split('/').length;
  var b_length = b.split('/').length;
  return a_length - b.length;
});
gijoe
  • 1,159
  • 7
  • 7