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
CodePudding user response:
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));
CodePudding user response:
var set =[
['N', 'N', 'Y', 'N'],
['1', 'N', '2', 'N'],
['N', '1', '4', 'N'],
['2', 'N', 'N', '1']];
let output = [];
set.forEach(array=>{
let count = 0;
array.forEach(letter =>{
if (letter === "N"){
count
}
})
output.push(count);
})
console.log(output);
//if you want to count by column
output = [0,0,0,0];
set.forEach(array=>{
for(let a=0;a<array.length;a ){
if (array[a] === "N"){
output[a]
}
}
})
console.log(output);
loop through your outer array passing each array into the function....then loop the the innerArray and check if the letter is "N" ....if so...increment count.....then push to the output array