将一个数组分成两个数组

Dividing an array into two arrays

我有一个包含 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], ...])放到单独的数组中。 我想我需要 foreachforeach.

你可以用简单的 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));

这是多种方法之一(它使用 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]]);
});

不是很漂亮,但我觉得可读性更好:

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"]

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

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