I am trying to find repeated words in a string and keep a count of how many times it was repeated. How do I do it in javascript.
let checkWords = "I am not gonna live forever, but I wanna live while I am alive";
I am looking for output like this I = 3, am = 2, not = 1 and so on, also is it possible to find the individual letter as I = 3, a = 6, m = 2.
I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here
let str = "I am not gonna live forever, but I wanna live while I am alive",
split = str.split(" "),
obj = {};
for (let i = 0; i < split.length; i++) {
if (obj[split[i]] === undefined) {
obj[split[i]] = 1;
} else {
obj[split[i]]++;
}
}
console.log(obj)