In JavaScript, I want to count the number of times "N" in is in the first, second, third, fourth column. I want each other there values. I want to get the number of occurrences in an array in array, and then get four numbers equal the occurrences.
input:
var set =[
['N', 'N', 'Y', 'N'],
['1', 'N', '2', 'N'],
['N', '1', '4', 'N'],
['2', 'N', 'N', '1']]
output: 3 2 2 2
const set = [
['N', 'N', 'Y', 'N'],
['1', 'N', '2', 'N'],
['N', '1', '4', 'N'],
['2', 'N', 'N', '1'],
];
const countNs = row => row.reduce((acc, curr) => acc + (curr === 'N' ? 1 : 0), 0);
// number of Ns in each row
console.log(set.map(countNs));
const transpose = a => a[0].map((_, c) => a.map(r => r[c]));
// Number of Ns in each column
console.log(transpose(set).map(countNs));
The total count for the column-occurrence of a given value from a table needs to follow an approach similar to transposing a table into a matrix.
An generic implementation based on two nested reduce tasks then might look like the next provided code ...
// function transpose(result, row) {
// return row.reduce((matrix, value, idx) => {
//
// (matrix[idx] ??= []).push(value);
// return matrix;
//
// }, result);
// }
function aggregateColumnValueCount(collector, row) {
// return row.reduce(({ value, counts = {} }, currentValue, idx) => {
return row.reduce(({ value, counts = [] }, currentValue, currentColumn) => {
// const currentColumn = `column_${ idx + 1 }`;
const currentCount = (counts[currentColumn] ??= 0);
if (currentValue === value) {
counts[currentColumn] = currentCount + 1;
}
return { value, counts };
}, collector);
}
const table = [
['N', 'N', 'Y', 'N'],
['1', 'N', '2', 'N'],
['N', '1', '4', 'N'],
['2', 'N', 'N', '1'],
];
console.log(
"column counts for value 'N' ...",
table
.reduce(aggregateColumnValueCount, {
value: 'N',
counts: [],
// counts: {},
}).counts
);
console.log(
// table.reduce(aggregateColumnValueCount, { value: '2', counts: {} })
table.reduce(aggregateColumnValueCount, { value: '2', counts: [] })
);
.as-console-wrapper { min-height: 100%!important; top: 0; }