You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.
Examples:
[7, 1] => [1, 7]
[5, 8, 6, 3, 4] => [3, 8, 6, 5, 4]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]
function sortArray(array) {
const hideOdds = array.map((e) => e % 2 === 0 ? e : "");
const odd = array.filter((e) => e % 2 !== 0).sort((a, b) => a - b);
const result = [];
for (let i = 0, oddIndex = 0; i < array.length; i += 1) {
if (hideOdds[i] === '') {
result.push(odd[oddIndex]);
oddIndex++;
} else {
result.push(hideOdds[i])
}
}
return result;
}
function sortArray(array) {
const odd = array.filter((x) => x % 2).sort((a,b) => a - b);
return array.map((x) => x % 2 ? odd.shift() : x);
}
The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is 0, undefined is returned.
shift is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.
array.shift()
The removed element from the array; undefined if the array is empty.
source: mdn web docs