Many of the solutions available around the internet for Bonfire: Where art thou are quite not right even if they pass the tests in FreeCodeCamp (FCC) because they don't adhere to the instructions completely.
- Disclaimer: Please don't look into the solutions if you've not solved it yourself.
Make a function that looks through a list (first argument) and returns an array of all objects that have equivalent property values (second argument).
Here are two solutions that exactly adhere to the instructions given in the Bonfire Challenge.
function where(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function (obj) {
// return a Boolean value for filter callback using reduce method
return srcKeys.reduce(function (res, key) {
// reduce to Boolean value to be returned by reduce method
return obj.hasOwnProperty(key) && obj[key] === source[key];
}, false);
});
}
// should output: [ { first: 'Tybalt', last: 'Capulet' } ]
console.log(where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' }));
// should output: [ { a: 5, b: 10 } ]
console.log(where([{ 'a': 5 }, { 'a': 5 }, { 'a': 5, 'b': 10 }], { 'a': 5, 'b': 10 }));
function where(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function (obj) {
for(var i = 0; i < srcKeys.length; i++) {
// check if obj in collection doesn't have the key
// or if it does have the key,
// then check if the property value doesn't match the value in source
if(!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) {
return false;
}
}
return true;
});
}
// should output: [ { first: 'Tybalt', last: 'Capulet' } ]
console.log(where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' }));
// should output: [ { a: 5, b: 10 } ]
console.log(where([{ 'a': 5 }, { 'a': 5 }, { 'a': 5, 'b': 10 }], { 'a': 5, 'b': 10 }));