Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract columns from a 2D array?

Scenario:

I have a 2 Dimensional array consisting of values, for example:

const arr = [ [ 1, 2, 3, 4, 5, 6 ],
              [ 7, 8, 9, 0, 1, 2 ],
              [ 3, 4, 5, 6, 7, 8 ],
              [ 9, 0, 1, 2, 3, 4 ] ];

The number of rows can vary, though will always be a multiple of two.

Question:

How can I extract columns out of this array using .map() so that I can get sub-arrays each containing two columns?

Example:

// columns 1 and 2:
ext1 = [ [ 1, 2 ],
         [ 7, 8 ],
         [ 3, 4 ],
         [ 9, 0 ] ];

// columns 3 and 4:
ext2 = [ [ 3, 4 ],
         [ 9, 0 ],
         [ 5, 6 ],
         [ 1, 2 ] ];

// columns 5 and 6:
ext3 = [ [ 5, 6 ],
         [ 1, 2 ],
         [ 7, 8 ],
         [ 3, 4 ] ];
like image 591
I hope this is helpful to you Avatar asked Oct 27 '25 10:10

I hope this is helpful to you


2 Answers

You can make a function like this that selects columns based on an array of indices:

const getColumns = (arr, indices) => arr.map(row => indices.map(i => row[i]));
getColumns(arr, [0, 1]);    // returns the first two columns

If the ultimate aim is to split the array into equal size chunks you could do it like this:

const splitIntoColumnGroups = (arr, width) => 
  [...Array(Math.ceil(arr[0].length/width)).keys()].map(i => 
    arr.map(row => 
      row.slice(i * width, (i + 1) * width)));
like image 187
Stuart Avatar answered Oct 29 '25 23:10

Stuart


You can do it with using map and filter as:

const arr = [ [ 1, 2, 3, 4, 5, 6 ],
              [ 7, 8, 9, 0, 1, 2 ],
              [ 3, 4, 5, 6, 7, 8 ],
              [ 9, 0, 1, 2, 3, 4 ] ];

function fn(array, firstIndex, secondIndex) {
    return array.map(a => a.filter((b,i) => i == firstIndex || i == secondIndex));
}

var result = fn(arr, 2, 3);
console.log(result);
like image 29
Tatranskymedved Avatar answered Oct 30 '25 00:10

Tatranskymedved



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!