简体   繁体   English

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

[英]Find index of same elements in array multiple times

I'd like to find an element's POSITIONS in same array without methods, with an algorithm... 我想在没有方法的情况下使用算法在同一数组中找到元素的位置 ...

Example : 范例

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

What I have done so far: 到目前为止,我所做的是:

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

For getting all positions, you must walk whole array before return 为了获得所有位置,您必须在返回之前遍历整个数组

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]

I'd suggest: 我建议:

count (haystack, needle) {
    return haystack.filter(function (el, index) {
        if (el === needle) {
            return index;
        }
    });
}

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

相关问题 如何在同一个数组中找到多个元素的索引 - how find the index of multiple elements in the same array 查找具有多个元素的二维数组的索引 - Find Index of 2D Array with multiple Elements 如何多次使用具有相同元素的数组 - How to work with an array that has the same elements multiple times 如何在多维数组中将多个元素插入到同一个索引中? - How to insert multiple elements into the same index in a multidimensional array? 如何使用第二个数组元素查找数组中多个元素的索引,然后使用结果匹配第三个数组的索引(Javascript) - How to find indexes of multiple elements in array with second array elements and then use result to match index of third array (Javascript) 在 JavaScript 中多次重复包含多个元素的数组 - Repeat an array with multiple elements multiple times in JavaScript 查找数组中“索引”应用程序出现的次数 - Find how many times “Index” appers in array 如何使用键多次将相同的方法应用于不同的数组元素? - How to apply the same method multiple times to different array elements using a key? 在嵌套数组中查找多个元素 - Find multiple elements in nested array 单击索引的元素,具有相同标识符的多个元素 - Clicking element by index, multiple elements with same identifier
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM