javascript - 多次查找数组中相同元素的索引

标签 javascript arrays algorithm

我想在同一个数组中找到一个元素的POSITIONS,没有方法,有一个算法...

示例:

var a = [1,2,2,1,4,5,6]
to display positions of 1 : position 0 and 3
to display positions of 2 : position 1 and 2

到目前为止我做了什么:

function count(array,element){
    while(element in array){
        return array.indexOf(element);
    }
}

最佳答案

为了得到所有的位置,你必须在返回之前遍历整个数组

var a = [1,2,2,1,4,5,6]

function count(array,element){
  var counts = [];
    for (i = 0; i < array.length; i++){
      if (array[i] === element) {  
        counts.push(i);
      }
    }
  return counts;
}

count(a, 1); //returns [0,3]
count(a, 2); //returns [1,2]

关于javascript - 多次查找数组中相同元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27443170/

相关文章:

php - 为什么以 null 作为回调的 array_map() 创建一个 "array of arrays"?

php - 如何通过连接从 MySQL select 获取嵌套数组

c++ - 为嵌套循环计算大 O

algorithm - 决定 {0^2^n; 的图灵机; n>0} 这不是普遍接受的

javascript - { ...obj1, obj2 } 到底做什么

javascript - 使用 javascript 验证提交的表单

javascript - 在网页标题栏中显示计时器

javascript - VS Code断点跳转到其他行

c++ - 重复符号拱 X86_64

algorithm - 找出n个节点的所有可能的连通图和有向图的数量