【问题标题】:Dividing an array into two arrays将一个数组分成两个数组
【发布时间】:2019-05-03 23:15:45
【问题描述】:

我有一个包含 n 个节点的数组(行)。每个节点包含 6 个元素。

示例:

rows[0]: ["1", "Text", "0", "55", "0", "Text 2"]
rows[1]: ["2", "Another Text", "15.5", "55", "16.6", "Another Text 2"]
...
rows[n]: [...]

我想将所有行 [n] 中的第二个元素(如 ["Text", "Another Text", ...]) 放入单独的数组中

和

我也想将第三个和第五个元素(如[[0, 0], [15.5, 16.6], ...])放入单独的数组中。 我想我在foreach 中需要foreach。

【问题讨论】:

  • 向我们展示您的尝试。使用各种不同的循环方法有很多方法可以做到这一点
  • rows.map((arr) => arr[n])?
  • 试试看。始终先尝试 - 然后向我们展示您的方法。通过这样做,您将学到更多,而不是通过复制/粘贴某人不可避免地会给您的一些答案。 idownvotedbecau.se/noattempt

标签: javascript arrays sub-array


【解决方案1】:

这是多种方法之一(它使用Array#forEach),

let arrays = [
 ["1", "Text", "0", "55", "0", "Text 2"],
 ["2", "Another Text", "15.5", "55", "16.6", "Another Text 2"]
];

let withIndex1 = [];
let withIndex2And4 = [];

arrays.forEach((arr) => {
  withIndex1.push(arr[1]);
  withIndex2And4.push([arr[2],arr[4]]);
});

【讨论】:

    【解决方案2】:

    你可以用简单的Array#map:

    const rows = [
       ["1", "Text", "0", "55", "0", "Text 2"],
       ["2", "Another Text", "15.5", "55", "16.6", "Another Text 2"],
    ];
    
    const r = (d, n) => rows.map((arr) => arr[n]);
    
    console.log(r(rows, 1));
    console.log(r(rows, 2));

    【讨论】:

    • 看起来不错,但 console.log(r(rows, 1)); console.log(r(rows, 2, 4)); 不起作用
    【解决方案3】:

    不是那么漂亮,但我认为更具可读性:

    let row = [
        ["1", "Text", "0", "55", "0", "Text 2"],
        ["2", "Second Text", "15.5", "55", "16.6", "Second Text 2"],
        ["3", "Third Text", "17", "60", "18", "Third Text 2"]
    ];
    
    let arrA = [], arrB = [];
    
    function newArrA(el, arr) {
        arr.forEach(arrEl => arrA.push(arrEl[el-1]));
    }
    
    function newArrB(elA, elB, arr) {
    
        arr.forEach(arrEl => arrB.push( [ arrEl[elA-1], arrEl[elB-1] ] ) );
    
    }
    
    newArrA(2, row);
    // arrA: ["Text", "Second Text", "Third Text"]
    
    newArrB(3, 5, row);
    // arrB[0]: ["0", "0"]
    // arrB[1]: ["15.5", "16.6"]
    // arrB[2]: ["17", "18"]
    

    【讨论】:

      【解决方案4】:

      您可以转置矩阵并获取想要的列并再次转置以获得想要的结果。

      const
          transpose = (r, a) => a.map((v, i) => [...(r[i] || []), v]),
          array = [["1", "Text", "0", "55", "0", "Text 2"], ["2", "Another Text", "15.5", "55", "16.6", "Another Text 2"]],
          columns = array.reduce(transpose, []),
          ad1 = columns[1],
          ad2 = [columns[2], columns[4]].reduce(transpose, []);
      
      console.log(ad1);
      console.log(ad2);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-17
        • 2021-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        相关资源
        最近更新 更多