Algorithm_Wherefore art thou

Algorithm_Wherefore art thou
0

#1

Hello!
I have been stuck in this algortihm for some hours. I wrote 5 or 6 solutions that didn’t work for every item. Now, I finally solved it, but I feel it’s a stupid solution… at least very unorthodox. Can you please take a look at it and help me to think in a better way?

I think the basic algorithms were pretty easy and very enjoyable. However, I am taking a long time to solve these intermediate algorithms and when I do, it always seems that it’s not the best way at all.

Thank you for your attention! This is my code…

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line
  
  var propSource = Object.keys(source);
  var test = 0;
  
  arr = collection.filter(function(obj) {
    for (i=0; i<propSource.length; i++) {
      if (obj.hasOwnProperty(propSource[i]) && obj[propSource[i]] === source[propSource[i]]) {
        test += 1;
      } else {
        test += 0;
      }
      if (test === propSource.length) {
        test = 0;
        return true;
      }
    }
    test = 0;
  });
  
  // Only change code above this line
  return arr;
}

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

#2

Is the same as
if (obj.hasOwnProperty(propSource[i]) && obj[propSource[i]] === source[propSource[i]]) {
test++;
}

Another solution would be just going with a for loop through the collection-array and test with for…in loop through source if collection has the property and if the value of that property is the same as in source.


#3

You can also omit the .hasOwnProperty() call.

I think you can omit test = 0; before return true; since test is no longer used after the return.


#4

Yes… I feel so stupid with this kind of stuff… :confused: I think I will have to study javascript better before continuing the remaining algorithms.
Thank you for your comments!


#5

The .hasOwnProperty is really redundant. This one I have noticed by my own on other (failed) solutions I have came up with. Not on this specififc one… Thank you!

However, I can’t figure why if I omit the test = 0; before the return true; it doesn’t work for the second function call example:

whatIsInAName([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }], { "a": 1 }) should return [{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }]

Any idea?


#6

Ah! Because after the return the function stops and never resets the test variable, I think! :slight_smile: