I\'m trying to build a javascript function which would count the number of occurrences of each word in an input array.
Example :
Input
a=[\"a
function count(arr){
return arr.reduce(function(m,e){
m[e] = (+m[e]||0)+1; return m
},{});
}
The idea behind are
reduce
for elegancem[e]
to a number using +m[e]
to avoid the constructor
(or toString
) problemDemonstration
You can also create an array just by initializing [] as the initial accumulator.
var fruits = ['apple', 'orange', 'grape', 'apple'].reduce((countFruits,currentFruit)=>{
if(typeof countFruits[currentFruit]!=="undefined"){
countFruits[currentFruit] = countFruits[currentFruit]+1
return countFruits
}
countFruits[currentFruit] = 1
return countFruits
},[])
console.log(fruits)
var arr = ['apple', 'orange', 'grape', 'apple'];
var initialValue = {};
var result = arr.reduce(function(accumulator, curr, idx, arr) {
if (Object.hasOwnProperty.call(accumulator, curr)) { // does current exist as key on initialValue object?
accumulator[curr]++;
} else { // no key for current on initialValue object
accumulator[curr] = 1;
}
return accumulator;
}, initialValue);
console.log(result);