Couldn't understand the solution

Tell us what’s happening:

I did not understand how reduce and map are working. Can really anyone explain in as easy as possible. please

Your code so far

      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) {
    return srcKeys
      .map(function(key) {
        return obj.hasOwnProperty(key) && obj[key] === source[key];
      })
      .reduce(function(a, b) {
        return a && b;
      });
  });
}

// test here
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/79.0.3945.88 Safari/537.36.

Challenge: Wherefore art thou

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou

1 Like

this is one of the cases in which you shoud try to follow the values using pen and paper, it would help you a lot

map is doing something with each element in the srcKeys returning a boolean for each element depending on conditions
reduce takes the array of booleans and returns true if everything is true inside the array, otherwise it returns false

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Please don’t do it again.

Thank you.

I tried pen and paper i can understand that for first object in collection arr, { first: "Romeo", last: "Montague" }. map will check whether srcKeys value and key mathes this or not. If Yes then return ture, in the above case it return false. Then it goes to reduce now i don’t understand what is a and b here and why do we need reduce ?

Now i understand sorry

reduce is needed to pass from an array of boolean to a single value
a and b are the accumulator and the current value of the reduce callback function

1 Like

Got it thanks, so much