简体   繁体   English

如何提升奇数并将偶数保持在原位

[英]How to ascend odd numbers and keep even numbers in their places

As you can see in my code, the odd numbers are ascended, but the even numbers are eliminated.正如您在我的代码中看到的,奇数升序,但偶数被消除。 I want the even numbers to stay in their places.我希望偶数留在他们的位置。 The expected log would be [1, 3, 2, 8, 5, 4]预期的日志将是[1, 3, 2, 8, 5, 4]

 function sortArray(array) { let sortedNumbers = array.sort(); let newArray = []; for (let i = 0; i < sortedNumbers.length; i++) { if (sortedNumbers[i] % 2 !== 0) { newArray.push(sortedNumbers[i]); } } return newArray; } console.log(sortArray([5, 3, 2, 8, 1, 4]));

I think the clearest way to do this would be to extract all the odd numbers into a separate array, sort that array, then insert them back into the original array:我认为最清晰的方法是将所有奇数提取到一个单独的数组中,对该数组进行排序,然后将它们插入到原始数组中:

 function sortArray(array) { const odds = array.filter(num => num % 2 === 1); odds.sort((a, b) => a - b); return array.map( num => num % 2 === 1 ? odds.shift() : num ); } console.log(sortArray([5, 3, 2, 8, 1, 4]))

Note that you can't use .sort , because .sort compares lexicographically (eg 11 will come before 2 , which is wrong) - use .sort((a, b) => a - b);请注意,您不能使用.sort ,因为.sort字典顺序进行比较(例如11将在2之前出现,这是错误的) - 使用.sort((a, b) => a - b); instead.反而。

I'm not sure what "ascended" means, but for instance if you wanted to add 0.1 to each odd number while leaving the evens as they are, you could simply add an else statement as follows.我不确定“升序”是什么意思,但例如,如果您想在每个奇数上加上 0.1,而让偶数保持原样,您可以简单地添加一个else语句,如下所示。

Note that providing the numericSort function is necessary unless you want your numbers to be sorted alphabetically (which is the default for the .sort method.)请注意,除非您希望数字按字母顺序排序(这是.sort方法的默认设置),否则必须提供numericSort函数。

 const numericSort = (a, b) => a - b; function sortArray(arr) { const sortedNumbers = arr.sort(numericSort), newArray = []; for(num of sortedNumbers) { if (num % 2 !== 0) { newArray.push(num + 0.1); } else { newArray.push(num); } } return newArray; } console.log(sortArray([5, 31, 20, 8, 1, 4]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM