Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get number of occurrences in an array in array? Javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading