Today I will continue to do a question about arrays:
One difficulty here is that there are negative numbers in the numerical sorting. Sorting using sort will also report an error.
So, after several thoughts and tests, my answer is as follows:
function highAndLow(numbers){ var numArr=[],numArr1=[],numArr2=[]; numbers.split(' ').map(function(n){ if(n>=0){ numArr2.push(n); }else{ numArr1.push(n); } }); numArr1.sort((a,b)=>b-a); numArr2.sort((a,b)=>b-a); numArr = numArr2.concat(numArr1); numArr.splice(1,numArr.length-2); return numArr.join(' ') }
First divide the positive and negative numbers into two groups, then sort them separately, and finally merge the arrays , just take the first and last digits of the array.
The method is a bit stupid. Hahaha, I am that stupid bird.
Finally check out the code written by others:
The most practical one is
function highAndLow(numbers){ numbers = numbers.split(' ').map(Number); return Math.max.apply(0, numbers) + ' ' + Math.min.apply(0, numbers); }
directly uses the max and min methods of Math (I Why didn't you think of it? Pig head, 555...)
There is another one that is closest to my original idea:
function highAndLow(numbers){ var arr = numbers.split(' ').sort(function(a, b) { return a - b }); return arr[arr.length -1] + ' ' + arr[0]; }
It's just that I wrote it as
function highAndLow(numbers){ numbers.split(' ').sort((a, b)=> a - b }); numbers.splice(1,numbers.length-2); return numbers.join(' '); }
Because the numbers were not converted into an array, an error occurred (low-level error)
The above is the detailed content of Example tutorial of code war. For more information, please follow other related articles on the PHP Chinese website!