Don't understand JS Exercice: Wherefore art thou

Don't understand JS Exercice: Wherefore art thou
0.0 0

#1

Tell us what’s happening:
Hi,

I keep reviewing the Basic Code Solution and I can’t get a hang of it…I mean, I understand globally what’s going on, but not the statements in the for loop.

What is this code trying to do ? And why doesn’t it return an array? It returns a boolean value instead?

I don’t get it.

Additionnally I was doing my own code with for loops only, and not using the .filter method and returning an array with the first object and its properties, as asked in the exercice. Then I was stuck and I looked at the Basoc Code Solution and I was stunned.
Is there a way to code this exercise without using th .filter method?

Your code so far

Spoiler - working solution
function whatIsInAName(collection, source) {
  // "What's in a name? that which we call a rose
  // By any other name would smell as sweet.”
  // -- by William Shakespeare, Romeo and Juliet
  var srcKeys = Object.keys(source);

  // filter the collection
  return collection.filter(function (obj) {
    for(var i = 0; i < srcKeys.length; i++) {
      if(!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) {
        return false;
      }
    }
    return true;
  });
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0.

Link to the challenge:


#2

As a comparison between filter and the code necessary to write a filter imperatively:

Imperative (explicitly writing the steps needed) version:

var inputArray = [1,2,3,4,5,6,7,8];
var output array = [];

for (var i = 0; i < inputArray.length; i++) {
  if (inputArray[i] < 5) {
    outputArray.push(inputArray[i];
  }
}

return outputArray;

Filter version:

var inputArray = [1,2,3,4,5,6,7,8];
var outputArray = inputArray.filter(function(v) {
  return v < 5;
});
return output array;

The Boolean return value in the filter is functionally the same as the one in the if statement. The filter loops through the array, and for any value that returns true, it puts it into the new array it returns.


#3

If you use filter and every with arrow functions, there’s actually a fairly simple one-line solution:

Spoiler
return collection.filter(el => Object.keys(source).every(key => el[key] === source[key]));

Changing the arrow functions to traditional functions and formatting nicely, you’d get this:

Spoiler
return collection.filter(function(el) {
  return Object.keys(source).every(function(key) {
    return el[key] === source[key];
  });
});

I highly recommend reading up on unfamiliar methods on MDN when you come across them:

(I’ve also spoilered the code in your original post, because it’s a working solution to the challenge.)