Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

415
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!