Home > Mobile >  How to remove an array from a nested array, loop throug the rest of the arrays. And then loop throug
How to remove an array from a nested array, loop throug the rest of the arrays. And then loop throug

Time:11-30

let linkMatrix = [
    [0,0,1,0],
    [1,0,0,1],
    [1,1,0,1],
    [0,1,0,0]
];


let newMatrix = [];

function linkToPage(){

    for(let j = 0; j < linkMatrix.length; j--){
        newMatrix = linkMatrix.splice(linkMatrix[j], 1);
        console.log(linkMatrix   " Here is linkMatrix");

        
            for(let i = 0; i < newMatrix.length; i  ){
                newMatrix.splice(newMatrix[i]);
                console.log(newMatrix   " Here is newMatrix");
            }
        
    }

**What i'm trying to do is loop throug the first array but remove the fist array, because i don't need to loop throug that, then loop throug the rest of the arrays, but the only value i need is the value in the removed array's index, so to better understand: if we had an array that wore somthing like this arr = [[0,1],[1,0],[1,1]] then remove [0,1] and because it is arr[0], i would like to loop throug the 0 index of the other arrays so i would get 1 and 1, then go back to the original array remove arr[1] and loop throug arr[0],arr[2] to the 1 index of the arrays so i would get [1,1] **

**Yeah, so the wanted result from my link matrix would be: 
    [0,0,1,0] = 2 
    [1,0,0,1] = 2
    [1,1,0,1] = 1
    [0,1,0,0] = 2
because there is 2 other arrys pointing to the first array, the same for the second and fourth, but there is only one array pointing to the third array
    **

CodePudding user response:

You could add the values of the columns.

const
    getColSum = matrix => matrix.reduce((r, a) => a.map((v, i) => (r[i] || 0)   v), []);

console.log(...getColSum([[0, 0, 1, 0], [1, 0, 0, 1], [1, 1, 0, 1], [0, 1, 0, 0]]));
console.log(...getColSum([[0, 0, 0], [1, 0, 0], [1, 1, 0]]));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

A version without (nearly) array methods.

function getColSum (matrix) {
    const result = Array(matrix[0].length).fill(0);

    for (const row of matrix) {
        for (let i = 0; i < row.length; i  ) result[i]  = row[i];
    }

    return result;
}

console.log(...getColSum([[0, 0, 1, 0], [1, 0, 0, 1], [1, 1, 0, 1], [0, 1, 0, 0]]));
console.log(...getColSum([[0, 0, 0], [1, 0, 0], [1, 1, 0]]));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related