Create a 5 x 5 matrix of all pair values coming from an array

Hey guys so I am trying to create a 5×5 matrix where all the values should be pair numbers. Everything goes well in like the first two tries, it actually prints

2 4 6 8 10
12 14 16 18 20

but then it becomes

16 18 20 22 24
20 22 24 26 28

I used the debugger and it turns out that my aux is 15 when j reaches 20, and since j = aux, then j goes back, and that’s causing the issue, how do I increment aux so that this issue does not occur?

function matrix(array) {
    const row = 5
    let column = 5
    let aux = 0
    for (let i = 0; i < row; i++) {
        const newArray = []
        for (let j = aux; j < column + aux; j++) {
            if (newArray.length < 5) {
                if (array[j] % 2 == 0) {
                    newArray.push(array[j])
                    console.log(array[j])
                }
                else {
                    column++
                }
            }
            aux = column
        }
    }
}
matrix([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50])

Answer

You might be over-complicating this slightly. You can do this without a nested loop, and therefore without the aux variable. You simply need one loop that loops through the array that is passed to the function, like so:

    function matrix(array) {
        var newArray = [];
        for(let i = 0; i < array.length; i++) {
            if(array[i] % 2 == 0) {
                newArray.push(array[i]);
                if(newArray.length==5) {
                    console.log(newArray);
                    newArray = [];
                }
            }
        }
    }
    
    matrix([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]);