Sort Only Odds

Sort Only Odds and keep evens in the same index using javascript

by jacobwsmith

JavaScript

function sortArray(arr) {
	let oddsSorted = arr.filter(item => (item%2) ? true: false).sort().reverse();
  return arr.map(function(el, index, array){
  	if((array[index]%2)){
    	return oddsSorted.pop();
    }else{
      return array[index];
    }
  });
};

/// TESTING ///
function assertArray(actual, expected) {
  const meetsReq = expected.every((item, index) => {
    return item === actual[index];
  });
  if (meetsReq) {
    console.log('passed')
  } else {
    console.log(`FAILED expected \"${expected}\"  but got \"${actual}\"`)
  }
}
assertArray(sortArray([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]), [10, 1, 8, 3, 6, 5, 4, 7, 2, 9]);
assertArray(sortArray([10, 5, 7, 12, 1, 9, 4, 6]), [10, 1, 5, 12, 7, 9, 4, 6]);
assertArray(sortArray([5, 3, 2, 8, 1, 4]), [1, 3, 2, 8, 5, 4]);
assertArray(sortArray([]), []);