-1

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?

웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
user3238361
  • 15
  • 1
  • 6

1 Answers1

2

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);
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67