javascript odd and even separation in an array of numbers

前端 未结 5 1664
一整个雨季
一整个雨季 2021-01-06 19:04

i wants to separate an array with two groups (odd and even) sequentially. but when i try this:

5条回答
  •  我在风中等你
    2021-01-06 19:34

    Because you move every found even value to the end of the array:

    0: 1 2 3 4 5 6 7 8 9
         ^-------------v
    1: 1 3 4 5 6 7 8 9 2   3 is not checked, because of the incremented index after splicing
           ^-----------v
    2: 1 3 5 6 7 8 9 2 4   5 is not checked
             ^---------v
    3: 1 3 5 7 8 9 2 4 6   7 is not checked
               ^-------v
    4: 1 3 5 7 9 2 4 6 8   9 is not checked
                 ^-----v
    5: 1 3 5 7 9 4 6 8 2
                   ^---v
    6: 1 3 5 7 9 4 8 2 6
                     ^-v
    7: 1 3 5 7 9 4 8 6 2
                       |
    8: 1 3 5 7 9 4 8 6 2
    

    But, you do not check the value after the found even value, like the value 3 in line zero, because it is never checked and stays at this place, as well as other actually uneven values. You could try the whole again with all even at the beginning of the array, like

    var array = [2, 4, 6, 8, 1, 3, 5, 7, 9];
        
    for (var i = 0; i < array.length; i++) {
        if (array[i] % 2 === 0) {
            array.push(array.splice(i, 1)[0]);
            console.log(i + ': ' + array.join(' '));
        }
    }
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Solution

    You could use a length for checking and reduce the length for every found even value. In this case, the index stays at the value, because at the index is now the next element for checking.

    var array = [1, 2, 3, 4, 5, 6, 7, 8, 9],
        i = 0,
        l = array.length;
    
    while (i < l) {
        if (array[i] % 2 === 0) {
            array.push(array.splice(i, 1)[0]);
            l--;
            continue;
        }
        i++;
    }
    
    console.log(array);

    Or just sort.

    By moving odd values to top and then sort by value.

    var array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    array.sort((a, b) => b % 2 - a % 2 || a - b);
    console.log(array);

提交回复
热议问题