JS 序列中出现的次数是质数

JS Number of occurences in a sequence is a prime number

我有两个数组(X 和 Y),我需要创建数组 Z,它包含数组 X 中的所有元素,但在数组 Y 中出现 p 次的元素除外,其中 p 是质数。 我想用 JS 写这个。

例如:
数组 X: [2, 3, 9, 2, 5, 1, 3, 7, 10]
数组 Y: [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
阵列 Z: [2, 9, 2, 5, 7, 10]

到目前为止我有这个:

const arrX = [2, 3, 9, 2, 5, 1, 3, 7, 10]
const arrY = [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
const arrZ = []
const counts = [];

// count number occurrences in arrY
for (const num of arrY) {
  counts[num] = counts[num] ? counts[num] + 1 : 1;
}

// check if number is prime
const checkPrime = num => {
    for (let i = 2; i < num; i++) if (num % i === 0) return false
    return true
}

console.log(counts[10]);
// returns 4

感谢任何提示或帮助。谢谢!

你走在正确的轨道上。 counts 应该是一个对象,将 arrY 中的元素映射到它们的出现次数。 reduce.

很容易得到

素数检查需要稍作修改,最后一步是过滤 arrX。过滤器谓词只是对该元素计数的主要检查。

// produce an object who's keys are elements in the array
// and whose values are the number of times each value appears
const count = arr => {
  return arr.reduce((acc, n) => {
    acc[n] = acc[n] ? acc[n]+1 : 1;
    return acc;
  }, {})
}

// OP prime check is fine, but should handle the 0,1 and negative cases:
const checkPrime = num => {
    for (let i = 2; i < num; i++) if (num % i === 0) return false
    return num > 1;
}

// Now just filter with the tools you built...
const arrX = [2, 3, 9, 2, 5, 1, 3, 7, 10]
const arrY = [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
const counts =  count(arrY);
const arrZ = arrX.filter(n => checkPrime(counts[n]));
console.log(arrZ)