繁体   English   中英

如何从嵌套数组中删除数组,循环遍历 arrays 的 rest。 然后循环遍历嵌套 arrays 的 1 值,全部在 vanilla js 中

[英]How to remove an array from a nested array, loop throug the rest of the arrays. And then loop throug 1 value of the nested arrays, all in vanilla js

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");
            }
        
    }

**我要做的是循环通过第一个数组但删除第一个数组,因为我不需要循环通过它,然后循环通过 arrays 的 rest,但我需要的唯一值是值在删除的数组的索引中,以便更好地理解:如果我们有一个数组穿着像这样的东西 arr = [[0,1],[1,0],[1,1]] 然后删除 [0,1] 和因为它是 arr[0],我想循环通过另一个 arrays 的 0 索引所以我会得到 1 和 1,然后 go 回到原始数组删除 arr[1] 并循环通过 arr[0],arr [2] 到 arrays 的 1 索引,所以我会得到 [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
    **

您可以添加列的值。

 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]]));

没有(几乎)数组方法的版本。

 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]]));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM