You just should stop do arr = collection.filter when it found first “false”.
If you put something like that:
for (let j =0;j<sorNames.length;j++){
arr = collection.filter(x=> {
let found = Object.is((x)[sorNames[j]],(source)[sorNames[j]]);
console.log( found );
return found;
});
console.log(arr);
};
Yo can see it in the console.
The second iteration returns false… and the result is [], but the last one returns true and it returns: {a: 1, b: 2, c: 3}…
You just stop “filtering” in the second iteration, also feels like it should be “while” and not filter.
This is my modified answer for this quiz. After your comment I understood what was the problem with my code. When filter function at least one time passes all test with arguments provided it will return array no meter what even when the second argument from collection was not good. In this modified answer at the beginning there is checking if collection.length > 1 if so filter function is making its magic . If collection.length === 1 there is checking if every item in collection and source equals . Maybe I could use while as you suggested but I’m trying to work with filter and forEach and more build functions so I get use to it.
function whatIsInAName(collection, source) {
let arr;
/*array for checking if collection === source when collection.length =1*/
let arrTrue = [];
let names = Object.values(collection[0]);
/*source values*/
let sorValues = Object.values(source);
/*source property names*/
let sorNames = Object.getOwnPropertyNames(source);
if (collection.length > 1){
sorNames.forEach(function(name){
arr = collection.filter(x=>
x.hasOwnProperty(name) &&
Object.is((x)[name],(source)[name]) &&
Object.getOwnPropertyNames(x).length>=(sorNames.length) );});}
else {
sorNames.forEach(function(ele){
sorValues.forEach(function(eleme){
if (collection[0][ele] === eleme && collection[0].hasOwnProperty(ele) && names.includes(eleme)){
arrTrue.push(ele);
}
})
})
if (arrTrue.length === sorValues.length){
arr = collection;
} else {
arr = [];
}
}
return arr;
}