In addition to my last reply. I noticed why my program isn’t returning an empty array for test cases. For the majority of the test cases, if the property existed in both objects then the value always matched up. There was no difference. However, in these last two test cases the values are different for the same property name.
function whatIsInAName(objArr, sourceObj) {
const newArray = []; // Array to be returned
let elementMatch;
console.log("Array of Objects:");
console.log(objArr);
console.log("\nSource Object:");
console.log(sourceObj);
console.log("\n");
for (const element of objArr) {
console.log("Current Object from Array:");
console.log(element);
console.log("\n");
objectLoop: for (const prop in sourceObj) {
elementMatch = false;
for (const arrProp in element) {
if (element.hasOwnProperty(prop) === true) {
if (element[arrProp] === sourceObj[prop]) {
elementMatch = true;
}
// I try to add else { break objectLoop; } here, but it leads to me failing other tests.
}
else {
break objectLoop;
}
}
}
if (elementMatch === true) {
if (newArray.includes(element) === false) {
console.log("Element being added to new array:");
console.log(element);
console.log("\n");
newArray.push(element);
}
}
}
console.log("\n");
return newArray;
}
console.log(whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}));
I realized this was leading to the same issue where the property didn’t match, so it just continued to the next iteration and elementMatch was made true again then the element was pushed to the new array. I fixed this with the else branch where I exit the loop I named, so that this overwrite could be avoided.
As you can see in my code, I added a comment for what I wanted to add. However, when I implemented this else branch for if the values did not match it led to various other test cases failing and it didn’t work as I intended.
So, the logic is if the properties match then check if the values match. If the property doesn’t match then skip that element from the array of objects (each element being an object). If the property matches but the value doesn’t match then I want to apply the same logic. If the values don’t match then skip that element. However, it still pushes that element to the new array and just makes my program fail a bunch of other test cases.
