【问题标题】:Javascript Sort by character appearance positionJavascript按字符出现位置排序
【发布时间】:2022-10-05 16:39:00
【问题描述】:

我有以下代码:

<!DOCTYPE html>
<html>
<body>

<p id=\"demo\"></p>

<script>
    const input = \'hello world\';
    document.getElementById(\"demo\").innerHTML = sortAlphabets(input);

    function sortAlphabets(input) {
        return input.split(\'\').sort().join(\'\');
    };
</script>

</body>
</html>

结果是:dehllloorw

但我想将其更改为按角色出现位置排序。结果应该是:hellloowrd

我怎样才能做到这一点?

    标签: javascript sorting


    【解决方案1】:

    您可以使用带有.sort 的比较函数,在该函数中您可以使用input.indexOf 来获取输入字符串中字符第一次出现的索引。

    input.split('').sort((a,b) => input.indexOf(a)-input.indexOf(b)).join('')
    

    编辑

    如果要删除空格,只需在拆分后使用过滤器。

    input.split('').filter(c=>c!==' ').sort((a,b) => input.indexOf(a)-input.indexOf(b)).join('')
    

    【讨论】:

    • 最后添加拆分并加入,以便删除空间
    【解决方案2】:

    您需要一个自定义排序功能,这里将按索引进行比较

    const input = 'hello world';
    
    let splited = input.split('').map(e => e.trim());
    
    let sorted = splited.sort((a, b) => {
      return splited.indexOf(a) - splited.indexOf(b);
    }).join('');
    
    console.log(sorted);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-01
      • 2011-10-16
      • 2022-06-13
      • 2014-12-12
      • 2016-08-16
      • 2015-10-29
      • 2013-01-02
      • 2012-08-15
      相关资源
      最近更新 更多