Ham*_*teu 2 javascript sorting
我有以下代码:
<!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>
Run Code Online (Sandbox Code Playgroud)
结果是:dehllloorw
但我想将其更改为按角色出现位置排序。结果应该是:hellloowrd
我怎样才能做到这一点?
您可以在该函数中使用比较函数,.sort并在该函数内使用该函数input.indexOf来获取输入字符串中字符第一次出现的索引。
input.split('').sort((a,b) => input.indexOf(a)-input.indexOf(b)).join('')
Run Code Online (Sandbox Code Playgroud)
如果您想删除空格,只需在拆分后使用过滤器即可。
input.split('').filter(c=>c!==' ').sort((a,b) => input.indexOf(a)-input.indexOf(b)).join('')
Run Code Online (Sandbox Code Playgroud)