Questions about advanced use of filter to compare objects

I was reading this code as a part of a quest to better understand filter. 1) I don’t understand why the function is not using curly brackets after the statement. 2) I debugged this and saw that if I get rid of the curly brackets AFTER the reduce function closes, instead of having an object I just have prop3 returned. why? (Is this a special technique?)

// this function return the property-value pairs whose values are in acceptedValues
const acceptedValues = ["value1", "value3"]
const myObject = {
  prop1: "value1",
  prop2: "value2",
  prop3: "value3"

var filteredObject = Object.keys(myObject).reduce(function(r, e) {
  if (acceptedValues.includes(myObject[e])) r[e] = myObject[e] //HERE question 1)
  return r;
}, {}) // HERE question 2)

console.log(filteredObject)//--> should  be { prop1: 'value1', prop3: 'value3' }

If you mean why are there no curly braces around r[e] = myObject[e], it’s because they are technically not required for a one-line if block.

if (thing) console.log('the thing is true')
// is technically the same as 
if (thing) {
    console.log('the thing is true');
// but many people find the second easier to read

the {} in the reduce function is the initial value. It will be the original value of r in this case.

More here:

1 Like

Thank you.!
Ariel I read the MDN. I got this: initValue is needed if you want your reduce function starting at 0 index.
In this case: the initValue {} is provided to initialize obj (the first parameter of this reduce function)?

Thank you :slightly_smiling_face:

It isn’t called obj in the code above, but yes. You’ve got it :+1:

Sorry I was reading other case right off the bat and confused the names. We were taking about r. :sweat_smile:
Thank you!