How to sort elements in array without changing other elements indexes?

One option is to keep track of the indicies of the odd numbers in the original array, and after .reduceing and sorting, then iterate through the original odd indicies and reassign, taking from the sorted odd array:

function oddSort(array) {
  const oddIndicies = [];
  const newArr = array.slice();
  const sortedOdd = array.reduce((arr, val, index) => {
    if (val % 2 !== 0) {
      arr.push(val);
      oddIndicies.push(index);
    }
    return arr;
  }, [])
    .sort((a, b) => a - b);
  while (oddIndicies.length > 0) {
    newArr[oddIndicies.shift()] = sortedOdd.shift();
  }
  return newArr;
}

console.log(oddSort([5, 3, 2, 8, 1, 4]));
console.log(oddSort([5, 3, 2, 8, 1, 4, 11 ]));

First sort only the odd numbers and put it in an array oddSorted. Then map through each element in the original array and check if the current element is odd, if odd replace it with the corresponding sorted number from the oddSorted array.

function sortOddElements(arr){
   var oddSorted = arr.filter(ele => ele %2 != 0).sort((a, b) => a - b);
   var evenNotSorted = arr.map((ele, idx) => {
       if(ele % 2 != 0){
           return oddSorted.shift(); 
       }
       return ele;
     });
   return evenNotSorted;
}
var arr = [5, 3, 2, 8, 1, 4];
console.log(sortOddElements(arr));
arr = [5, 3, 2, 8, 1, 4, 11 ];
console.log(sortOddElements(arr));

Tags:

Javascript