You can utilize the JSON.stringify()
method to transform an object into a string that matches your desired output.
Ensure that you assign to the innerHTML
within the count()
function instead of simply returning the object.
The count()
function does not require a parameter as it extracts the string directly from the input value.
function count() {
var string = document.getElementById("myInput1").value;
let counts = string.split("").reduce((a, letter) => {
a[letter] = (a[letter] || 0) + 1;
return a;
}, {});
document.getElementById("output1").innerHTML = JSON.stringify(counts);
}
<h3>input</h3>
<input id="myInput1" type="text">
<button onclick="count()">View output</button>
<p id="output1"></p>