I'm writing a helper function to get every nth
element from an array in order to get all table cells for a specific column based on a column's index.
I've based on the answer from this thread.
My concern is that whenever I pass column index 0 it does not work. I am also not too sure what the delta should be changed to because it does not produce correct results.
Given the following array
const cells = [
'text', 'text', 'text', 'text', 'text', 'text', 'button',
'text', 'text', 'text', 'text', 'text', 'text', 'button',
'text', 'text', 'text', 'text', 'text', 'text', 'button',
];
and calling the function by getColumnCells(cells, 6)
I should be receiving an array of 'button's.
const getColumnCells = (cells, columnIndex) => {
const columnCells = [];
const delta = Math.floor(cells.length / columnIndex);
for (let i = columnIndex; i < cells.length; i = i + delta) {
columnCells.push(cells[i]);
}
return columnCells;
};
getColumnCells(cells, 0)
should return ['text', 'text', 'text]
to get the index 0 of every row.