javascript - Why won't Array.prototype.reduce() take an empty object literal as the initialValue? -
i'm working way through functional-javascript-workshop tutorial recommended nodejs (exercise 6).
i've written following simple code, supposed count occurrence of every word in array, , return results object each key-value pair word: # of occurrences.
function countwords (inputwords) { return inputwords.reduce(function (obj, current) { obj[current] = typeof obj[current] === 'number' ? obj[current] + 1 : 1; }, {}); } if run countwords(['bob']) error: uncaught typeerror: cannot read property 'bob' of undefined. carat points typeof obj[current] expression on third line.
if console.log(obj) on first line of reduce() function, outputs object {}. if console.log(typeof obj) on first line, outputs object. why think it's undefined? syntax not allowed?
the return value of function used obj argument next value in inputwords. since don't return explicitly, javascript returns undefined. why getting error. fix that, need return obj.
function countwords (inputwords) { return inputwords.reduce(function (obj, current) { obj[current] = typeof obj[current] === 'number' ? obj.current + 1 : 1; return obj; // return accumulated value }, {}); } anyway, logic can simplified bit, considering fact unknown keys return undefined default, this
function countwords(inputwords) { return inputwords.reduce(function (obj, current) { obj[current] = (obj[current] || 0) + 1; return obj; // return accumulated value }, {}); }
Comments
Post a Comment