I completed the challenge alright.
However, as my understanding of it goes, we can’t use forEach to do the looping instead of for, cause forEach doesn’t return anything. Right?
Or can forEach be implemented here, and if so how?
You asked if it could be done with forEach. It can and what I showed you above is one possible solution. I would look into using the method named every or the method named some to replace the for loop.
If you notice the “set-up” of the challenge, there’s a arr empty and ready to be filled with the values.
This actually incentives the usage of forEach, all you have to do is:
for each element that matches, add it into the array
Or in code:
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// For each element that pass match push it into array
collection.forEach(r =>
matches(r, source) && arr.push(r)
)
// Only change code above this line
return arr;
}
/**
* Compares two objects to determine if the first one contains equivalent property values to the second one.
* @param {object} obj
* @param {object} source
* @returns {boolean}
*/
const matches = (obj, source) =>
Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
```