Help improving code

I just finished up the intermediate algorithm “Wherefore art thou” and I’m passing all the tests, but I feel like my code could be more efficient. What coding priciples or methods would help my code be neater or more effecient?

  **My code**

function whatIsInAName(collection, source) {
const arr = [];
// Only change code below this line
for(let i = 0; i < collection.length; i++) {
  let obj = collection[i];
  let count = 0;
  for(let key in obj) {
    if(obj[key] == source[key]) {
      count++;
    }
  }
  if(count == Object.keys(source).length) {
    arr.push(obj);
  }
}
console.log(arr);
// 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 });
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.30

Challenge: Wherefore art thou

Link to the challenge:

I think a lot of people would recommend a functional approach to solving this. I’m not sure if that would be more efficient but I think it would probably be more readable, which is probably more important than being efficient.

So get rid of the for loop and use array methods that allow you to filter out only those objects in the array that meet the requirements.

1 Like