forked from sgrouples/javascript-assignment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex07.js
32 lines (24 loc) · 734 Bytes
/
ex07.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
Given an Array of strings, use Array#reduce to create an object that contains the number of times each string occured in the array. Return the object directly (no need to console.log).
Example
var inputWords = ['Apple', 'Banana', 'Apple', 'Durian', 'Durian', 'Durian']
console.log(countWords(inputWords))
// =>
// {
// Apple: 2,
// Banana: 1,
// Durian: 3
// }
*/
function countWords(words) {
return words.reduce(function(acc, word) {
if(acc.hasOwnProperty(word)) {
acc[word] = acc[word] + 1;
} else {
acc[word] = 1;
}
return acc;
}, {});
}
var inputWords = ['Apple', 'Banana', 'Apple', 'Durian', 'Durian', 'Durian']
console.log(countWords(inputWords))