-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"
]
1

2 Answers 2

3
strings.sort(function(a, b) {
    return a.split("/").length - b.split("/").length;
});
Sign up to request clarification or add additional context in comments.

Comments

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;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.