[英]How do I sort an array based on the count of a character in a string?
我在一个数组中有几个字符串。
例如:
[
"path/to/file",
"path",
"path/to/",
"path2/to/file",
"path2/to/file",
"path2/to"
]
等等...
我想要实现的是根据斜杠的计数对数组进行排序。 所以较少的计数在顶部斜线。
所以它会是这样的:
[
"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;
});
您将需要像这样使用数组排序方法的自定义函数
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.