Intermediate Algorithm Scripting - Wherefore art thou

Tell us what’s happening:

I was wondering if someone could help explain why this isn’t working. My idea was to have a seperate function which tests whether an object contains a particular key and value pairing, and then loop over the object and the key/values it’s looking for.

If at any point the key/value is not found, break out of that loop and move to the next object, if ALL key/values are found, push that object to the finalArray and move on.

But this only seems to return an empty array. If anyone could give me any hints it would be much appreciated!

Your code so far

function hasKeySetTo(obj,key,value)
{
    return obj.hasOwnProperty(key) && obj[key]==value;
}

function whatIsInAName(collection, source) {
 
   let keysArray = Object.keys(source);
   let valuesArray = Object.values(source);
   let finalArray = [];
   
  for (let i = 0; i < collection.length; i++){
    for (let j = 0; j < source.length; j++){
      if(hasKeySetTo(collection[i], keysArray[j], valuesArray[j]) === false){
        break; 
      }
      if(j === source.length - 1){
        finalArray.push(collection[i]); 
      }
    }   
  } 
  return finalArray;  
}

console.log(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/109.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Wherefore art thou

Link to the challenge:

Try adding couple of the console.log calls to narrow down, when your expectations don’t met what’s actually happening. It could be as simple as printing out the finallArray after each iteration, along the values that are current at the time.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.