2021年3月29日星期一

Javascript: Having Trouble Understanding Empty Initializer in Reduce Function

Stared at this one for at least 4 hours before finally deciding to reach out to you experts.

New to JS. The goal of this practice exercise was to create an object from some given key-value pairs. I did it one way which worked, however, I'm having a hard time understanding this sample solution provided:

const object_From_Pairs = arr => arr.reduce((a, v) =>     ((a[v[0]] = v[1]), a), {});  console.log(object_From_Pairs([['Title', 'Oliver Twist'], ['Author', 'Charles Dickens']]));  // Output: {Title: "Oliver Twist", Author: "Charles Dickens"}  

I understand how to use the reduce function, but I'm getting confused about what happens when you pass through an empty initializer value like {} or [].

According to the MDN web docs on the reduce function, the first time you go through the loop, your accumulator will be the initializer value that you can optionally provide (after the comma), and your value will be the value of the first item in the array you're passing through.

If that line of thinking is correct, it seems that my initial a value would be {}, and my v value would be the first subarray in the array, so ['Title', 'Oliver Twist']. However, when I tried going through the steps like that, my results weren't making sense. My train of thought went something like this:

arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {})  
  1. a = {} and v = ['Title', 'Oliver Twist']

  2. Replacing the a's and v's in the expression, we would have:

    arr.reduce((a, v) => (({}[['Title', 'Oliver Twist'][0]] = ['Title', 'Oliver Twist'][1]), {}), {})

  3. The [0] index value of v is 'Title', and the [1] index value of v is 'Oliver Twist', so we could shorten the expression to:

    arr.reduce((a, v) => (({}Title = Oliver Twist), {}), {})

  4. Here is where I start to get confused, because then after running through the reduce function the first time, it seems my new accumulator or a value would be ({}Title = Oliver Twist), {}), and that doesn't make sense when I try to substitute it into a the second time around.

What am I missing? Is {} not the initializer? Does {} just tell it to surround the resulting answer in the {}? Having trouble understanding how this formats into an object with the key: value pairs so nicely!

https://stackoverflow.com/questions/66863480/javascript-having-trouble-understanding-empty-initializer-in-reduce-function March 30, 2021 at 08:58AM

没有评论:

发表评论