Hello,
In the code below, I try to create a pure function, but it doesn’t work.
I get an Error: false is not a function.
Is there anything I can do to fix it.
Thank you.
Spoiler
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// a pure function
// that checks the matching proprties/values
let getProperties = function(arr, source) {
for (var i = 0; i < arr.length; i++) {
for (let prop in source) {
console.log('arr', arr[i][prop]);
console.log('source ', source[prop]);
if (arr[i][prop] !== source[prop]) {
return false
}
}
return true
}
}
arr = collection.filter(getProperties(collection, source));
return arr;
}
console.log(whatIsInAName([{
"apple": 1,
"bat": 2
}, {
"bat": 2
}, {
"apple": 1,
"bat": 2,
"cookie": 2
}], {
"bat": 2,
"apple": 1
}));
That is not how you pass a callback function to filter, you are running getProperties, not passing it as a callback.
// Check the console to see what is getting passed to the callback
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// a pure function
// that checks the matching proprties/values
let getProperties = function (ele, index, array) {
console.log(ele, index, array);
}
arr = collection.filter(getProperties);
return arr;
}
Spoiler
// Here is version that seems to work
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// a pure function
// that checks the matching proprties/values
let getProperties = function (ele) {
for (const key in source) {
if (source[key] != ele[key]) {
return false;
}
}
return true;
}
arr = collection.filter(getProperties);
return arr;
}
Why do you add true after the for loop ends instead of say putting in an else statement after the if statement? Aren’t we resetting the value to true for the filter function for every property when the true returns after the for loop?