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.
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 ] ];
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)));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With