将一维数组的元素分组以在Javascript中形成锯齿状二维数组

时间:2019-12-17 01:01:59

标签: javascript multidimensional-array

我的目标是选择1D数组B的元素,根据它们在1D数组B中的位置将它们分组为子数组。它们在数组B中的位置(索引)在2D数组索引中提供。

const B = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.01, 1.1, 1.2, 1.5];
const indices =  [ [ 3, 4, 5 ], [ 7, 8 ], [ 10, 11 ] ];

//Getting the elements from array B but flattened
const arrs = [];
for (let i = 0; i < indices.length; i++) {
    for (let j = 0; j < indices[i].length; j++) {
        arrs.push(B[indices[i][j]]);
    }
}
console.log("arrs", arrs)

//Converting the flattened array to 2D
var newArr = [];
let k = indices.length
while (k--) {
    newArr.push(arrs.splice(0, indices[k].length));
}

console.log("newArr", newArr);

我所做的是使用嵌套的for循环来尝试获取所需的输出,但是数组arrs被展平了。然后,我将展平的数组arrs转换为2D数组newArr。有没有更优雅,更直接的方法?

2 个答案:

答案 0 :(得分:1)

您可以在内部数组上使用.map(),并将每个元素用作B数组的索引。这仍然需要一个嵌套循环,因为您需要遍历每个内部数组以及该内部数组中的每个元素:

const B = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.01, 1.1, 1.2, 1.5];
const indices =  [ [ 3, 4, 5 ], [ 7, 8 ], [ 10, 11 ] ];

const newArr = indices.map(
  arr => arr.map(idx => B[idx])
);

console.log("newArr", newArr);

答案 1 :(得分:1)

执行两次map()操作即可

const array = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.01, 1.1, 1.2, 1.5];
const indices =  [ [ 3, 4, 5 ], [ 7, 8 ], [ 10, 11 ] ];

const result = indices.map(a => a.map(i => array[i]));

console.log(result);