Let’s say I have the following object:
const myObjects = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Alice", age: 30 },
{ name: "David", age: 25 }
];
I wrote the following function, so that the objects with the specified same props are returned in a new array:
function findObjectsWithSameProperties(objects, property1, property2) {
// Create an empty array to store the results
const matchingObjects = [];
// Loop through each object in the array
for (const obj of objects) {
// Check if the object has both specified properties
if (obj.hasOwnProperty(property1) && obj.hasOwnProperty(property2)) {
// Check if the values of the specified properties are the same
if (obj[property1] === obj[property2]) {
// If they are, add the object to the results array
matchingObjects.push(obj);
}
}
}
// Return the array of matching objects
return matchingObjects;
}
However, my function isn’t returning anything when I expect it to return this:
[
{ name: "Alice", age: 30 },
{ name: "Alice", age: 30 },
];
Here’s how I’m calling the function: findObjectsWithSameProperties(myObjects, "age", "name");
Does anyone know what I’m doing wrong? Here’s a CodePen link: https://codepen.io/obliviga/pen/WNWNbMX?editors=0011
2
Answers
You’re looping through objects, checking whether the object has both props and then checking whether the
name === age
. Furthermore you’re checking the same object’s properties so you won’t find duplicates either. This will obviously never be true. I suggest adding a history of the ones you’ve already looped through and then comparing whether it has already seen the same object or not.try this :