0

i am currently learning how to program using javascript, i came across a problem ( Write function that sort an array with odd first and even later // sortArray([3,24,1,4,9,10]) => [1,3,9,4,10,24] // sortArray([2,1,4,9,3,3,10,12]) => [1,3,3,9,2,4,10,12]), i have implemented a solution making use of the sort function and multiple variables. See code below;

  function sortingArr (array) {
    let sortedArr = (array.sort(function(a, b) { return a - b; })), oddArr = [], evenArr = [];
    for (i = 0; i < array.length; i++){
        if (sortedArr[i] % 2 == 0){
            evenArr.push(sortedArr[i]);
        }
        else {
            oddArr.push(sortedArr[i]);
        }
    }
    return oddArr.concat(evenArr);
}
console.log (sortingArr ([2,1,4,9,3,3,10,12]));

I would appreciate suggestions I can use to solve the same problem with minimal memory allocation and runtime.

Mr X
  • 129
  • 2
  • 16

3 Answers3

3

Sorting on 'a' having a smaller modulus 2 than 'b'
OR 'a' is bigger than 'b'.

function sortArrayUnevenFirst (array) {
    return array.sort(function(a,b){return b%2-a%2 || a-b});
}
console.log (sortArrayUnevenFirst([12,10,2,1,4,9,3,3]));
console.log (sortArrayUnevenFirst(['12','10','2','1','4','9','3','3']));

A modulus 2 can only be 0 for the even, and 1 for the uneven.

So when a%2==0 (even) and b%2==1 (uneven) then 'a' is put after 'b'.
And when a%2 equals b%2, then the size decides which comes first.

LukStorms
  • 28,916
  • 5
  • 31
  • 45
1

You could use a group for sorting even and odd numbers and then sort by value with a chained approach.

function sort(array) {
    return array.sort((a, b) => b % 2 - a % 2 || a - b)
}

console.log(sort([3, 24, 1, 4, 9, 10]));
console.log(sort([2, 1, 4, 9, 3, 3, 10, 12]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Pass your own compare function to sort.

const sorted = [2,1,4,9,3,3,10,12].sort((a, b) => {
    if(a % 2 === 1 && b % 2 === 1) return a - b;
    if(a % 2 === 1) return -1;
    if(b % 2 === 1) return 1;
    return a - b
})
console.log(sorted);
Alexandre Annic
  • 9,942
  • 5
  • 36
  • 50