【问题标题】:How do I sort an array based on the count of a character in a string?如何根据字符串中字符的计数对数组进行排序?
【发布时间】:2023-04-05 13:48:01
【问题描述】:

我在一个数组中有几个字符串。

例如:

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

【问题讨论】:

标签: javascript sorting


【解决方案1】:
strings.sort(function(a, b) {
    return a.split("/").length - b.split("/").length;
});

【讨论】:

    【解决方案2】:

    您将需要像这样使用数组排序方法的自定义功能

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

    【讨论】:

      猜你喜欢
      • 2021-08-17
      • 2017-09-11
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      相关资源
      最近更新 更多