Can you guys give me some direction in this Algorithm challenge?

First of all, the link: Intermediate Algorithm Scripting: Wherefore art thou

So by now I´m passing 3 of 6 tests with this messy code:

function prob(obj, source){
	var objectContainer = [];
	var definitive = "";
    Object.getOwnPropertyNames(source).forEach(function(val, idx, array) {
        //if (source) === val
       var objectSourc = val + source[val];
	   definitive = objectSourc

for (var i = 0; i < obj.length; i++){
        Object.getOwnPropertyNames(obj[i]).forEach(function(val, idx, array) {
		console.log(val + obj[i][val])
        if (definitive === (val + obj[i][val])){
		return objectContainer

I got the forEach function from Mozilla docs and The problem is, I have only been able to modify it to return an individual string for each iteration of each key of each object in the collection array (the first array it is provided). Then I compare it the individual string of source (the second argument) . If it´s the same then I push the whole object of 1st argument into the objectContainer array.

The problem this makes that with only one of the various keys passed in the second argument being in the first, then the function its true, when it should be true only when all of the arguments in the second are in the first. But i can´t wrap my head into how to concatenate that working with strings (i know, messy?)

For example whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }) should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }] .

However my code returns , in addition to [{ “apple”: 1, “bat”: 2 }, { “apple”: 1, “bat”: 2, “cookie”: 2 }], it also returns { “bat”: 2 }, when it shouldn´t

Something like:

SET output TO empty array

# Iterate through each object in the collection
FOR item OF collection
  # In the condition, iterate through all keys in source. If, for each one,
  # source[key] === item[key], then the condition is true.
  IF FOR EVERY key IN source, source[key] is equal to object[key] THEN
    # If it is true, then can push the current object to the output array
    add current object to output
  # Otherwise, do nothing and move onto the next item

RETURN output

This way can be done very cleanly with two loops + an one if (and Object.keys or Object.getOwnPropertyNames). It can also be done using filter, then using Object.keys + every in the callback.

Note you don’t need to check if the keys of source are in the current item in collection, you only need to check if the values for source[key] are equal to currentItem[key]; if the key isn’t present then neither will the value be

1 Like

Very helpful point that helps avoid unnecessary work/logic.