Understanding return value of a function

So I'm doing some challenges on freecodecamp, I got stuck on one that says: "Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument)." So I looked the for the answer and came accross the next code:

function whatIsInAName(collection, source) {
  var arr = [];
  var keys = Object.keys(source);
  // Filter array and remove the ones that do not have the keys from source.
  arr = collection.filter(function(obj) {
    return keys.every(function(key) {
      return obj.hasOwnProperty(key) && obj[key] === source[key];
    });
  });

  return arr;
}

I understand what it does what I cant seem to get is the returns inside the collection.filter why do we need these two:

    return keys.every(function(key) {
      return obj.hasOwnProperty(key) && obj[key] === source[key];

Why the code doesn't work with only the second one.

Can someone explain this to me please.

Upvotes: 2

Views: 214

Answers (2)

RizkiDPrast
RizkiDPrast

Reputation: 1725

this code:

arr = collection.filter(function(obj) {
    return keys.every(function(key) {
      return obj.hasOwnProperty(key) && obj[key] === source[key];
    });

First, (this is the main script to check wheter Collection's element match or not with the source)

keys.every(function(key) {
          return obj.hasOwnProperty(key) && obj[key] === source[key];

It will just return either true/false based on obj.hasOwnProperty(key) && obj[key] === source[key]; condition. it checks every keys from source. If it finds just one key un-matched with the condition it will break the loop and return false otherwise (passed all the test [all keys and values from source the same with collection's element]) return true.

then

arr = collection.filter(function(obj) { return true // false

if it return true, the element obj from collection will be passed to arr otherwise filtered / skipped

Upvotes: 1

castletheperson
castletheperson

Reputation: 33476

collection.filter is calling Array.prototype.filter. It is used for removing elements from an array that don't meet certain criteria. The function passed as a parameter is used to determine whether an element meets that criteria. A return value of false means that the element should be removed from the array, while true means that the element should stay in the array.

If you don't give the function a return statement, it will return undefined for all of the elements of the array, which is a falsy value.

In ES6, you can use arrow functions which don't require you to write return:

function whatIsInAName(collection, source) {
  var keys = Object.keys(source);
  return collection.filter(obj =>
    keys.every(key =>
      obj.hasOwnProperty(key) && obj[key] === source[key];
    )
  );
}

Upvotes: 0

Related Questions