Q:

Extract text from html tags using reduce in Javascript

I'm trying to concatenate the inner HTML of each paragraph tag on my page in one single string using reduce. Here's my try:

// JS
let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a, b) => a + ", " + b.innerHTML));
<!-- HTML -->
<p>Apple</p>
<p>Strawberry</p>
<p>Banana</p>

And here's the (wrong) output:

[object HTMLParagraphElement], Strawberry, Banana

What am I doing wrong?
Many thanks for your help!

A:

reduce function takes a 2nd argument which is the initial value for the accumulator.
By default, it's the first item in the array.
To have the desired result you should write your code like this:
let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a,b)=>a+", "+b.innerHTML, ""));

Here is a document on reduce function from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=a

