Posts

Showing posts from January 18, 2019

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

Image
11 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. javascript share |...