1

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?

2 Answers 2

1

You could use .map() on your inner arrays and use each element as an index for your B array. This still requires a nested loop as you need to go through each inner array, and each element in that inner array:

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

Sign up to request clarification or add additional context in comments.

Comments

1

A double map() operation will do it:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.