0

I have read the code in how to flatten an array in MDN in JS. And works fine, but I don't understand why isn't working in this case:

const data = [null, ['a', 'b', 'c']]
const flattened = data.reduce((acc, cur) => {
    if(null != cur)
        acc.concat(cur)
}, [])

And this error:

TypeError: Cannot read property 'concat' of undefined

How to correct this?

  • If the purpose is to filter null values (or false values maybe?) out, you could also do that early one by using Array#sort: `data.filter(cur => cur !== null).reduce((acc, cur) => acc.concat(cur), []);` – thibmaek May 14 '17 at 00:24
  • @naomik While the subject matter is addressed at linked Question, the specific issue at Question is not addressed by an Answer at linked Question. Is there a Question/Answer addressing no value being returned from `Array.prototype.reduce()` callback function? – guest271314 May 14 '17 at 00:38
  • @thibmaek I wanted to iterate only once over the array, that's why I choose just the reduce. If I had used a filter before it would iterate over again by the reduce method. – Lucas Almeida Carotta May 14 '17 at 19:06

1 Answers1

4

No value is returned from function passed to .reduce()

const data = [null, ['a', 'b', 'c']]
const flattened = data.reduce((acc, cur) => {
        if (cur !== null)
          acc = acc.concat(cur);
        return acc   
}, []);

console.log(flattened);
guest271314
  • 1
  • 15
  • 104
  • 177