So I solved the challenge with the code below, but I know it would cause some complications if the source object ever had more than two keys. What are some ways I could simplify this to make it shorter and more efficient?
**My code so far: **
function whatIsInAName(collection, source) {
// new array that will be pushed to
let arr = [];
// array of the keys in the source object
let sourceKeys = Object.keys(source);
// array of the values in the source object
let sourceValues = Object.values(source);
console.log(sourceKeys);
console.log(sourceValues);
// looping through the collection array
for (let i = 0; i < collection.length; i++) {
// if there are multiple keys in the source object, we will have to check for sourceKeys[0], sourceKeys[1],
// sourceValues[0], and sourceValues[1]
if (sourceKeys.length > 1) {
// if the object has BOTH keys in the source object
if (collection[i].hasOwnProperty(sourceKeys[0]) && collection[i].hasOwnProperty(sourceKeys[1])) {
// and if the values in the source object exist in the object
if (Object.values(collection[i]).indexOf(sourceValues[0]) >= 0) {
if (Object.values(collection[i]).indexOf(sourceValues[1]) >= 0) {
arr.push(collection[i]);
}
}
}
// if there is only one key in the source object, we only have to account for the [0] index
} else if (sourceKeys.length === 1) {
// if the object has the key in the source object
if (collection[i].hasOwnProperty(sourceKeys[0])) {
// if the value in the source object exists in the object
if (Object.values(collection[i]).indexOf(sourceValues[0]) >= 0) {
arr.push(collection[i]);
}
}
}
}
// Only change code above this line
return arr;
}
whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 });
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou