'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?
Solution 1:[1]
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rohìt JÃndal |
