简体   繁体   中英

How do I sort an array based on the count of a character in a string?

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"
]
strings.sort(function(a, b) {
    return a.split("/").length - b.split("/").length;
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM