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

  • A+
Category:Languages

I have this array:

var arr = [5, 3, 2, 8, 1, 4]; 

I'm trying to sort ONLY the elements that are odd values so I want this

output:

[1, 3, 2, 8, 5, 4] 

As you can see the even elements don't change their position. Can anyone tell me what I'm missing? Here's my code:

function myFunction(array) {    var oddElements = array.reduce((arr, val, index) => {     if (val % 2 !== 0){       arr.push(val);     }     return arr.sort();   }, []);    return oddElements; } console.log(myFunction([5, 3, 2, 8, 1, 4]));

I know I can use slice to add elements to array, but I'm stuck on how to get the indexes and put the elements in the array.

 


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 temp = [...arr];    var oddSorted = temp.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));

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: