Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract subarray of Columns from a multidimensional array and mutate the original array to remove those columns JavaScript

I want to extract a subarray of Columns from a multidimensional array and mutate the original array to remove those columns in JavaScript

Ex: If I have an array

originalArray =
[
 [A, B, C, D, E, F],
 [a1,b1,c1,d1,e1,f1],
 [a2,b2,c2,d2,e2,f2],
 [a3,b3,c3,d3,e3,f3]
[  

Where A,B,C,D,E,F are headers
and I want to extract columns [4,0,3] in this order I would get

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

subArray =
[
 [E, A, D],
 [e1,a1,d1],
 [e2,a2,d2],
 [e3,a3,d3]
[


originalArray = 
[
 [B, C, F],
 [b1,c1,f1],
 [b2,c2,f2],
 [b3,c3,f3]
[  

I found this:
Extract subarray from a multidimensional array and mutate the original array

which does this for rows

let subArray = originalArray.reduce((accumulator, current, index) => {
    if (idxList.includes(index)) {
      //if the current index is included in the idxList array, 
      //push the current value to the accumulator
      accumulator.push(current);
    } else {
      //push the current value to the `tempArray`.
      tempArray.push(current)
    }
    return accumulator;
  }, []);

Then I will concatenate these two arrays

reorderedArray = […subArray, …originalArray]

Reduce seems like an interesting approach and it seems like it should be a simple fix but I have to admit I am having a hard time understanding Reduce

Thanks in advance for your assistance

>Solution :

You could add the missing indices to order and map the array by mapping nested array with the indices of order.

let
    data = [['A', 'B', 'C', 'D', 'E', 'F'], ['a1', 'b1', 'c1', 'd1', 'e1', 'f1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3']],
    order = [4, 0, 3],
    seen = new Set(order),
    i = 0;

while (order.length < data[0].length) {
    while (seen.has(i)) ++i;
    order.push(i++);
}

data = data.map(a => order.map(i => a[i]));

data.forEach(a => console.log(...a));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading