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

409
Vistas
when i = 3 i.e., 8 it should push into arr but it isn't. Why?

var intersect = function(nums1, nums2) {
  var arr = [];
  var obj = {};
  for (let i = 0; i < nums1.length; i++) {
    if (!(nums1[i] in obj)) {
      obj[nums1[i]] = 1;
    } else {
      obj[nums1[i]] += 1;
    }
  }
  console.log(obj)
  for (let i = 0; i < nums2.length; i++) {
    if (obj[nums2[i]] != 0 && obj[nums2[i]] != undefined) {

      //when i = 3 i.e., 8 it should push into arr but it isn't. Why?//

      arr.push(nums2[i]);
      obj[nums2[i]] -= 1;
    }
  }
  console.log(obj);
  return arr;
};

let nums1 = [4, 9, 5];
let nums2 = [9, 4, 9, 8, 4];
console.log(intersect(nums1, nums2));

According to the condition if(obj[nums2[i]]!=0 && obj[nums2[i]]!=undefined ) which is true in case when i = 3 i.e. 8 and it should push into my arr but it isn't! why?

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

0

when i = 3 i.e., 8 it should push into arr but it isn't. Why ?

To answer your question, obj[nums2[i]] != 0 && obj[nums2[i]] != undefined condition will check for the nums2 array elements should be there in the obj. 8 as a property will not be available in the obj as it was missing in the nums1 array.

I think you should try this :

for (let i = 0; i < nums2.length; i++) {
    if (!(nums2[i] in obj)) {
      // push the nums2 element in the array if not available in the obj
      arr.push(nums2[i]);
      obj[nums2[i]] -= 1;
    }
}
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