Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort elements in array without changing other elements indexes? [duplicate]

Tags:

javascript

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.

like image 525
Devmix Avatar asked Jan 19 '19 05:01

Devmix


People also ask

How do you sort an array without changing original?

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.

Does sort mutate array?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.


2 Answers

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));
like image 97
Fullstack Guy Avatar answered Oct 18 '22 20:10

Fullstack Guy


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 ]));
like image 5
CertainPerformance Avatar answered Oct 18 '22 18:10

CertainPerformance