繁体   English   中英

如何获取数组中数组中的出现次数? Javascript

[英]How to get number of occurrences in an array in array? Javascript

在JavaScript中,我想统计is中的“N”在第一、二、三、四列出现的次数。 我要彼此有价值观。 我想获取数组中数组中出现的次数,然后得到四个数字等于出现次数。

输入:

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

表中给定值的列出现总数需要遵循类似于将表转置为矩阵的方法。

基于两个嵌套的reduce任务的通用实现可能看起来像下一个提供的代码......

 // 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; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM