JSFiddle - React, Tailwind, and code Playground
HTML
<div id="data">
Run the code below
</div>
JavaScript
var words = ['a', 'b', 'c', 'a', 'c', 'c'];
/*
The desired output is:
[
{word: 'a', weight: 2},
{word: 'b', weight: 1},
{word: 'c', weight: 3},
]
*/
var wordData = {}; // Edit, use {} intead of [] here.
for (var i = 0; i < words.length; i++) {
// The problem is definitely in this loop.
if (wordData.hasOwnProperty(words[i])) {
wordData[words[i]] += 1;
} else {
wordData[words[i]] = 1;
}
}
var results = [];
for (var prop in wordData) {
result = {word: prop, weight: wordData[prop]};
results.push(result);
}
var json_result = JSON.stringify(results, null, 2);
document.getElementById('data').innerHTML = json_result;