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

本文介绍了两个JavaScript编程挑战,分别涉及判断数组是否有序及对数组进行排序。第一个挑战是实现一个函数`isSortedAndHow`,它接受一个整数数组并返回数组是否按升序或降序排列。第二个挑战是完成`sortNumbers`函数,对传入的数字数组进行排序,如果数组为空则返回空数组。文章提供了作者的解决方案和测试用例,供读者参考学习。

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

codewars-js练习

2021/2/4

github 地址

my github地址,上面有做的习题记录,不断更新…

【1】<7kyu>【Sorted? yes? no? how?】

Complete the method which accepts an array of integers, and returns one of the following:

  • "yes, ascending" - if the numbers in the array are sorted in an ascending order
  • "yes, descending" - if the numbers in the array are sorted in a descending order
  • "no" - otherwise

example

it("[1, 2]", function() {
    Test.assertEquals(isSortedAndHow([1, 2]), 'yes, ascending');
  });
 it("[15, 7, 3, -8]", function() {
    Test.assertEquals(isSortedAndHow([15, 7, 3, -8]), 'yes, descending');
  }); 
  it("[4, 2, 30]", function() {
    Test.assertEquals(isSortedAndHow([4, 2, 30]), 'no');
  });

solution

<script type="text/javascript">
 		function isSortedAndHow(array) {
 			// console.log(array);
 			var array1 = JSON.parse(JSON.stringify(array));
 			var array2 = JSON.parse(JSON.stringify(array));
 			var array3 = JSON.parse(JSON.stringify(array));

 			// console.log('array深拷贝后',array1);

 			// 升序排序
 			var arr = array.sort((a,b)=>{return a-b});
 			// console.log('array升序排序后',arr);

 			// 降序排序
 			var arr1 = array3.sort((a,b)=>{return b-a});
 			// console.log('array降序排序后',arr1);

 			if(arr.toString() == array1.toString()){
 				return 'yes, ascending';
 			}else if(arr1.toString() == array2.toString()){
 				return 'yes, descending';
 			}else{
 				return 'no';
 			}		
 		}
 		// 验证
		console.log(isSortedAndHow([1,2])); // 'yes, ascending'
		console.log(isSortedAndHow([15, 7, 3, -8])); // 'yes, descending'
		console.log(isSortedAndHow([4, 2, 30]));//'no'
	</script>
【2】<7kyu>【Sort Numbers】

Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.

example

solution([1, 2, 10, 50, 5]); // should return [1,2,5,10,50]
solution(null); // should return []

solution

<script type="text/javascript">
 		function solution(nums){
 			// console.log(nums);
 			return (nums || []).sort((a, b)=>{return a - b});
 		}
 
 		// 验证
		console.log(solution([1,2,10,50,5])); // [1,2,5,10,50]
		console.log(solution(null)); //[]
	</script>

以上为自己思路供大家参考,可能有更优的思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值