Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
JS Number of occurences in a sequence is a prime number

I have two arrays (X and Y) and I need to create array Z that contains all elements from array X except those, that are present in array Y p times where p is a prime number. I am trying to write this in JS.

For Example:
Array X: [2, 3, 9, 2, 5, 1, 3, 7, 10]
Array Y: [2, 1, 3, 4, 3, 10, 6, 6, 1, 7, 10, 10, 10]
Array Z: [2, 9, 2, 5, 7, 10]

So far I have this:

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

Any hint or help appreciated. Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You're on the right track. counts should be an object mapping elements in arrY to their number of occurrences. It's easily gotten with reduce.

The prime check needs a minor edit, and the last step is to filter arrX. The filter predicate is just a prime check on the count for that element.

// 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) 

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda