codewars-js练习
2021/2/20
github 地址
【1】<7kyu>【Sort by Last Char】
Given a string of words (x), you need to return an array of the words, sorted alphabetically by the final character in each.
If two words have the same last letter, they returned array should show them in the order they appeared in the given string.
All inputs will be valid.
给定一个单词字符串(x),需要返回一个单词数组,按每个单词中的最后一个字符按字母顺序排序。如果两个单词的最后一个字母相同,它们返回的数组应该按照它们在给定字符串中出现的顺序显示它们。
example:
last('man i need a taxi up to ubud')//['a', 'need', 'ubud', 'i', 'taxi', 'man', 'to', 'up']);
solution
<script type="text/javascript">
function last(x){
// console.log((/^[ ]+$/).test(x))
var arr = x.split(' ')
if(!(/^[ ]+$/).test(x)){
return arr.sort((a,b)=>{return a[a.length-1].localeCompare(b[b.length-1])})
}
return arr;
}
// 验证
console.log(last('man i need a taxi up to ubud'));// ['a', 'need', 'ubud', 'i', 'taxi', 'man', 'to', 'up']
console.log(last(' '))
</script>
以上为自己思路供大家参考,可能有更优的思路。
以下为别人的思路。
function last(x){
return x.split(' ').sort((a, b) => a.charCodeAt(a.length - 1) - b.charCodeAt(b.length - 1));
}
这篇文章分享了如何在Codewars平台上解决一道关于JavaScript的7kyu等级题目,SortbyLastChar,要求根据单词的最后一个字符进行字母顺序排序,并展示了两种不同的解决方案。作者提供了自己的思路和他人的高效思路供读者参考。
295

被折叠的 条评论
为什么被折叠?



