Can anyone please explain to me a bit what exactly this “.reduce(function(a, b) { return a && b;})” do here? I don’t quite understand it.
// filter the collection
return collection.filter(function(obj) {
return srcKeys
.map(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
})
.reduce(function(a, b) { // what does this ".reduce" do here?
return a && b;
});
});
The reduce method receives an array from the map method, an array that will contain a number of Booleans (depending on the length of your srcKeys).
reduce will now iterate over that array, and in each step, it will compare the accumulator (the a parameter) and the current element (the b parameter) with &&, so it will only return true if both are true. The return value will go into reduce again in the next step as the new a parameter. So in the end, it will only return true if all values in that array were true. If there’s just one false, a will become false and the comparison a && b will always be false for all following steps.
In this particular case, you could also get the same result by using the every method on the array instead of reduce.