具有N(数组中的出现次数)和数组,如何获取数组中出现N的元素?

时间:2018-07-06 21:45:02

标签: javascript arrays list data-structures

例如N = 2,arr = [2,2,3,0,1,5,5]

如何从数组中获得2和5?

另一个例子是 N = 1 arr = [20,37,20,21]

我应该得到37和27。

3 个答案:

答案 0 :(得分:2)

您可以遍历数组以创建包含每个值计数的字典,然后找到count = N

var arr =  [2, 2, 3, 0, 1, 5, 5];
var N = 2;
var cnt = {};

for (var i = 0; i < arr.length; i++) {
  var num = arr[i];
  cnt[num] = cnt[num] ? cnt[num] + 1 : 1;
}


for(var it in cnt) {
   if(cnt[it] == N) {
       console.log(it);
   }
}

答案 1 :(得分:0)

对数组进行排序,对连续元素进行计数:

const result = [];
let count = 0, previous = null;
for(const el of arr.sort()) {
  if(el === previous) {
    count++;
  } else {
    if(count === N) result.push(N);
    count = 0;
    previous = el;
  }
}

答案 2 :(得分:0)

您可以将数字计数到一个计数对象中,然后进行过滤:

const arr = [2, 2, 3, 0, 1, 5, 5]
const n =  2

/* counts will be an object like {2: 2, 3: 1, 0:1 } */
let counts = arr.reduce((a,c) => (a[c] = a[c] ? a[c] + 1 : 1, a), {}) 

/* just return the keys where the corresponding value is n*/
let res = Object.keys(counts).filter(k => counts[k] == n)

console.log(res)