Intermediate Algorithm Scripting - Wherefore art thou

Tell us what’s happening:
Please ignore most of the console.log commands in my code, I used it for testing (I can also edit them out if neccessary). (Edit: Deleted them)
I always get an undefined array as a result and I’m not sure where my mistake is in the code. I’m checking first if the keys from the source object are in the elem object (elem is each array entry from collection), then I check if one of the values is equal to one of the values from source object. If both of this is true, the elem object gets pushed into the accumulator “arr”.

Your code so far

function whatIsInAName(collection, source) {
    var keyArrSrc = Object.keys(source)
  collection.reduce((arr, elem) =>{
    if(elem.hasOwnProperty(keyArrSrc)){
        let tmpArrVal1 = Object.values(elem)
        let tmpArrVal2 = Object.values(source)
        for(let i = 0; i<tmpArrVal1.length; i++){
            for(let j = 0; j<tmpArrVal2.length; j++){
                if(tmpArrVal1[i] == tmpArrVal2[j]){
                arr.push(elem)
                }
            }
        }
    }
    return arr
  }, [])
}

console.log(whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }));

Your browser information:

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

Challenge: Intermediate Algorithm Scripting - Wherefore art thou

Link to the challenge:

Can you explain big picture what you want this part to do? I think that it is intended to check if every key of the source has the same value in the current object, but it doesn’t do that. It pushes a reference to the current object every single time any key of the source has a matching value in the current object. So you will end up with a lot of references to the same object.

Also, don’t forget to have your callback function return something.

Also, I think you only need a double loop, not a triple loop.

I must admit the code is not finished yet and still needs to be improved regarding the correct output.

The code snippet you provided checks if the values of elem and source are equal, which was the task to check if the values are equal, which then get pushed into another seperate resulting array. I do see now that I could get the same multiple objects in the resulting array.

I also added return arr in the callback function (or did I skip one closing curly bracket? :sweat_smile:)

1 Like

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