My goal is to select elements of a 1D array,B, grouping them into subarrays based on their positions in the 1D array B. Their positions (indices) in array B are provided in the 2D array indices.
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);
What I have done is to use a nested for-loop to try to get the desired output, but the array arrs is flattened. Then, I converted the flattened array arrs to a 2D array newArr. Is there a more elegant and straight-forward approach?