title: Use reduce to sum values in array of objects
body: <p>I have this array of objects:</p>
  <pre><code>const data = [
    {val: 40, color: 'red'},
    {val: 5, color: 'green'},
    {val: 55, color: 'lime'}
  ]
  </code></pre>
  <p>This is what I would like to obtain:</p>
  <pre><code>const result = [
    {val: 40, color: 'red'},
    {val: 45, color: 'green'},
    {val: 100, color: 'lime'}
  ]
  </code></pre>
  <p>So each item should have the same color and the cumulative value of previous data.</p>
  <p>This is what I try:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [
    {val: 40, color: 'red'},
    {val: 5, color: 'green'},
    {val: 55, color: 'lime'}
  ]
  
  // const result = [
  //   {val: 40, color: 'red'},
  //   {val: 45, color: 'green'},
  //   {val: 100, color: 'lime'}
  // ]
  
  const result = data.reduce((r, value, i) =&gt; {
      const { val, color } = value
      const cumVal = i === 0 ? val : r[i - 1].val
      const newDatum = { val: cumVal, color }
      return newDatum
  }, data[0])
  
  console.log(result)</code></pre>
  </div>
  </div>
  </p>
  <p>Where is the error? Why <code>r[i - 1]</code> is undefined?</p>