Reduce method in Wherefore art thou

Tell us what’s happening:
Describe your issue in detail here.
i know that

 souceKeys
    .map(key => obj.hasOwnProperty(key) && obj[key] === source[key])

will giving array of boolean in this case [false] [false] [true]

so .reduce((a, b) => a && b)); in my mind is
.reduce((a,b ) => false && false)); // first run
.reduce((a,b) => false && true)); // second run

which will never return true in this case so how it acuallty work?

  **Your code so far**
function whatIsInAName(collection, source) {

const souceKeys = Object.keys(source);


return collection.filter(obj => souceKeys
    .map(key => obj.hasOwnProperty(key) && obj[key] === source[key])
    .reduce((a, b) => a && b));
}


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 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36

Challenge: Wherefore art thou

Link to the challenge:

Where does this array come from? Also, aren’t those three arrays?

callback that in the filter function executes for each object separately. So reduce will be invoked on array with only one element (and in this case reduce returns just that element)

you just can break the algorithm down in smaller pieces and print out the results to understand how it works

function whatIsInAName(collection, source) {

  const souceKeys = Object.keys(source);
  console.log("source keys:", souceKeys);

  return collection.filter((obj, i) => {
    console.log("current obj at index", i, obj);

    let res = souceKeys.map(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
    console.log("map result:", res);

    res = res.reduce((a, b) => a && b);
    console.log("reduce result:", res);
    console.log("----------------------");

    return res;
  });
}

whatIsInAName(
  [
    { first: "Romeo", last: "Montague" },
    { first: "Mercutio", last: null },
    { first: "Tybalt", last: "Capulet" }
  ],
  { last: "Capulet" }
);
1 Like
function whatIsInAName(collection, source)
{
    const souceKeys = Object.keys(source);


 return collection.filter(obj => console.log(souceKeys
.map(key => obj.hasOwnProperty(key) && obj[key] === source[key])));

}

can you use your own words?

Thanks it was super clear

I think I get it now,thank you @ilenia