codewars练习(javascript)-2021/2/20

这篇文章分享了如何在Codewars平台上解决一道关于JavaScript的7kyu等级题目,SortbyLastChar,要求根据单词的最后一个字符进行字母顺序排序,并展示了两种不同的解决方案。作者提供了自己的思路和他人的高效思路供读者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

codewars-js练习

2021/2/20

github 地址

my 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));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值