Search code examples
javascriptarraysgoogle-apps-scriptgoogle-sheetsv8

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

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