javascript - 搜索并计算特定命令在数组中出现的次数

标签 javascript arrays multidimensional-array

我已经搜索过了,但一无所获。这是我的测试用例的样子:

console.log(specificSearch([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ], 'even')); // the maximum number of even numbers is in row - 2, which are 2 and 8

  console.log(specificSearch([
  ['o', 'o', 'o', 'x'],
  ['x', 'x', 'o'],
  ['o', 'x'],
  ['x', 'x', 'x', 'x', 'x', 'x', 'x']
  ], 'x')); // the maximum number of x is in column - 4, which is 7 times appear

这是我目前的代码:

function specificSearch(array, command) {

    var max = 0
    var even = 0
    for(var i = 0; i < array.length; i++){
      var evenCounter = 0
       for(var j = 0; j < array[i].length; j++){
          if(command === 'even'){
             if(array[i][j] % 2 == 0){
                evenCounter++
             }
          } 
       }

       if(command === 'even' ){
         if( max < evenCounter) {
           max = evenCounter
           even = i
         }
       }
    }
    return even
  }

那是当我尝试搜索偶数时,如果它搜索数字然后它必须返回行和什么数字但另一方面如果它不搜索数字并且数组的长度不相同那么它需要返回什么列和多少次出现。 这种情况不需要内置函数,如正则表达式、映射、过滤器、索引,只需使用循环和数组操作,如 push、pop、shift 等

谢谢你的帮助,我只是一个尝试学习代码的菜鸟:)

最佳答案

您可以传递一个函数来检查特定值并返回一个 bool 值以进行检查。

  • 偶数

    x => !(x % 2)`
    
  • 进行身份验证

    x => x === 'x'
    

然后您可以收集行和列数组中的所有计数,稍后获取最大值并从 rows/cols 数组返回具有最大值的索引。

结果是一个对象,该对象具有行/列的最大计数以及出现最大计数的索引。

顺便说一句,这个答案使用索引,因为它们在 Javascript 中工作,从零开始。如果您需要从一个开始,只需为每个索引添加一个。

function specificSearch(array, checkFn) {

    function getIndices(array, value) {
        var i, indices = [];
        for (i = 0; i < array.length; i++) {
            if (array[i] === value) indices.push(i);
        }
        return indices;
    }

    var i, j,
        rows = [],
        cols = [],
        max;

    for (i = 0; i < array.length; i++) {
        for (j = 0; j < array[i].length; j++) {
            if (checkFn(array[i][j])) {
                rows[i] = (rows[i] || 0) + 1;
                cols[j] = (cols[j] || 0) + 1;
            }
        }
    }
    max = Math.max(...cols, ...rows);
    return { max, rows: getIndices(rows, max), cols: getIndices(cols, max) };
}

console.log(specificSearch([[1, 2, 3], [4, 5, 6], [7, 8, 9]], x => !(x % 2)));
console.log(specificSearch([['o', 'o', 'o', 'x'], ['x', 'x', 'o'], ['o', 'x'], ['x', 'x', 'x', 'x', 'x', 'x', 'x']], x => x === 'x'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 搜索并计算特定命令在数组中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54123855/

相关文章:

javascript - 暂时禁用事件监听器并稍后重新绑定(bind)

JavaScript 循环

javascript - 使用 DOM 组织表格中的元素 - JavaScript

java - 在 Java 中使用构造函数创建对象数组

java - 创建 Java 类

c - 二维矩阵的值未分配正确

javascript - jQuery : missing ; before statement

c++ - 使用列表进行动态结构分配

c++ - C/C++ 3维数组如何存储在内存中以及遍历它的最快方法是什么

javascript - 如何从一个公共(public)变量中的多个数组中获取名称 id?