Can someone explain the following code? inputWords is supposed to be an array containing various words and this function is supposed to return an array containing the number of times a word appears in inputWords.
ie. var inputWords = ['Apple', 'Banana', 'Apple', 'Durian', 'Durian', 'Durian']
console.log(countWords(inputWords))
// =>
// {
// Apple: 2,
// Banana: 1,
// Durian: 3
// }
I understand what the Reduce function does, but what is resultObj[word] = ++resultObj[word] || 1; doing?
Thanks so much :)
function countWords(inputWords) {
return inputWords.reduce(function(resultObj, word) {
resultObj[word] = ++resultObj[word] || 1;
return resultObj;
}, {});
}
module.exports = countWords;
resultObj[word]if it exists, otherwise initializes it to 1.||is the logical or operator, will pick the 1 if the left side is a falsy valuereduceis actually the operation of applying a function to aggregate a collection to a single value, in this case an array with many words to an object counting how many times each word appears in the array. The increment is what actually does the counting.resultObj[word] = (resultObj[word] || 0) + 1which gets the intention better across.