JSFiddle - React, Tailwind, and code Playground
by karim79
JavaScript
var words = "hello hello what what";
var wordArr = words.split(" "),
fd = [],
len = wordArr.length;
var addWord = function(str) {
if (fd.length) {
for (var i = 0; i < fd.length; i++) {
if (!fd[i][str]) {
fd.push({
word: str,
occurences: 1
});
} else {
fd[i].occurences++;
}
}
} else {
fd.push({
word: str,
occurences: 1
});
}
};
var populate = function() {
for (var i = 0; i < len; i++) {
addWord(wordArr[i]);
}
};
populate();
alert(fd[0].word + " " + fd[0].occurences);