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. Example sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
代码如下:
function sortArray(array) { var js = {},r=[]; for (var i = 0, l = array.length; i < l; i++) { if (array[i] % 2) { js[i] = array[i]; r.push(array[i]); } } r.sort(function(a,b){ return a-b }) var i=0; for(var k in js){ array[k]=r[i++] } return array }
测试:
console.log(sortArray([5, 3, 2, 8, 1, 4])); console.log(sortArray([5, 3, 1, 8, 0]));
结果:
[ 1, 3, 2, 8, 5, 4 ] [ 1, 3, 5, 8, 0 ]