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.
To sort an array, without mutating the original array:Call the slice() method on the array to get a copy. Call the sort() method on the copied array. The sort method will sort the copied array, without mutating the original.
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
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));
One option is to keep track of the indicies of the odd numbers in the original array, and after .reduce
ing 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 ]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With