I have an array my
array=["hello","goodbye","hello","hello","goodbye"];
and i want this array to count the occurrences of each word and print a table with each word and how many times is seen to the array in JavaScript. Can you help me please?
I have an array my
array=["hello","goodbye","hello","hello","goodbye"];
and i want this array to count the occurrences of each word and print a table with each word and how many times is seen to the array in JavaScript. Can you help me please?
Try this:
var array=["hello","goodbye","hello","hello","goodbye"];
var count = {};
for (var i = 0; i < array.length; i++) {
count[array[i]] = (count[array[i]] || 0) + 1;
}
console.log(count);
HTML Output:
var table = document.createElement('table');
for (var word in count) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + word + '</td><td>' + count[word] + '</td>';
table.appendChild(tr);
}
document.body.appendChild(table);