Javascript - Extract data from html table
Always use const to declare variables - only use let when you must reassign. This keeps code readable, because then a reader of the code doesn't have to constantly keep in mind that a variable might be reassigned later. (If you use let but then don't reassign, it can still be confusing - in professional code, one might think "Why is let being used here? Was this meant to be reassigned in a section of code that was later removed, or something?)

Array.from accepts an optional mapper function as a second parameter. Any time you have:

Array.from(arrayLike).map(mapper)


you may replace it with

Array.from(arrayLike, mapper)


(If all you're doing is converting an array-like object into an array, some prefer spread syntax because it's even more concise: [...arrayLike])

innerText is a weird property introduced by Internet Explorer (outside of web standards originally) that has a number of odd quirks. Unless you're deliberately looking to invoke those quirks, it would be a better idea to use textContent instead to retrieve text from an element.

You can easily distinguish the first tr from the other trs by using the query string #tab tr:first-child or #tab tr:nth-child(n + 2):



const headers = Array.from(
  document.querySelectorAll('#tab tr:first-child th'),
  th =&gt; th.textContent.trim()
);
// Make an empty array for every item in headers:
const data = Array.from(headers, () =&gt; []);
for (const tr of document.querySelectorAll('#tab tr:nth-child(n + 2)')) {
  [...tr.children].forEach((th, i) =&gt; {
    data[i].push(th.textContent.trim());
  });
}
console.log(headers);
console.log(data);
&lt;table id="tab"&gt;
  &lt;tr&gt;
    &lt;th&gt;
      Name
    &lt;/th&gt;
    &lt;th&gt;
      Age
    &lt;/th&gt;
    &lt;th&gt;
      Location
    &lt;/th&gt;
  &lt;/tr&gt;

  &lt;tr&gt;
    &lt;th&gt;
      Jason
    &lt;/th&gt;
    &lt;th&gt;
      22
    &lt;/th&gt;
    &lt;th&gt;
      Texas
    &lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;th&gt;
      Lawson
    &lt;/th&gt;
    &lt;th&gt;
      21
    &lt;/th&gt;
    &lt;th&gt;
      Florida
    &lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;th&gt;
      Jose
    &lt;/th&gt;
    &lt;th&gt;
      25
    &lt;/th&gt;
    &lt;th&gt;
      London
    &lt;/th&gt;
  &lt;/tr&gt;

&lt;/table&gt;




That's already quite simple, IMO. I think adding jQuery to the mix would make things unnecessarily more complicated, not less.

I refactored it out, but I don't think it's good idea to use reduce when the accumulator is going to be the same object every time. See: Is reduce bad? by Google devs. If it's always going to be the same object, it'll be a bit easier to read if that object is declared as a standalone variable in the outer scope.

The HTML is a bit weird. A &lt;th&gt; is a table header. It makes sense for the headers to be &lt;th&gt;s, but the table data should probably be &lt;td&gt;s instead.