Instructions
You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
给定一个数组,数组元素值类型为number,将其中元素为奇数的排序,偶数位置不变
Example:
sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
Test.assertSimilar(sortArray([5, 3, 2, 8, 1, 4]), [1, 3, 2, 8, 5, 4])
Test.assertSimilar(sortArray([5, 3, 1, 8, 0]), [1, 3, 5, 8, 0])
Test.assertSimilar(sortArray([]),[])
方法
function sortArray(array) {
let odds = array.filter(item => item % 2 !==0).sort((a,b) => a-b)
return array.map(item => item = item % 2 != 0 ? odds.shift() : item)
}
思路分析
用filter方法过滤出所有奇数元素并从小到大排序
用map 方法遍历参数数组,如果原数组的元素是奇数,就用odds数组元素替换
注意
ES5中提供的常用数组遍历方法ForEach, filter, map等都不改变原数组,返回值为遍历操作后的数组。