将一个数组分为两个数组

时间:2018-12-02 13:12:43

标签: javascript arrays sub-array

我有一个具有 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]: [...]

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

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

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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 :(得分:1)

不是很漂亮,但我认为它更具可读性:

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

答案 3 :(得分:0)

您可以转置矩阵并获取所需的列,然后再次转置以获得所需的结果。

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