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