0

I have a problem with this piece of code.

I import input data from a file formated like so and store it in const input:

aabcccccaaa
aaccb
shsudbud

There are no spaces or any other white characters except from '\n' newline.

I get inputs in this way: (LiveServer inside VS Code)

const getData = async () => {
  const resp = await fetch("./inputs.txt");
  const data = await resp.text();
  return data;
};

Then I call:

const myFunc = async () => {
  const input = await getData();
  const rows = input.split("\n").map(row => row);
  rows.forEach(row => {
    const charArr = [...row];
    console.log(charArr);
  });
};

After logging to console first and second row it seems like there is "" (empty string) attached to the end of each of them. The third element is fine so I guess its somehow connected with newline character.

I have also tried creating charArr by doing:

const charArr = Array.from(row);

Or

const charArr = row.split("");

But the outcome was the same.

Later I found this topic: Remove empty elements from an array in Javascript

So I tried:

const charArr = [...row].filter(Boolean);

But the "" is still at the end of charArr created from 1st and 2nd row.

const input = `aabcccccaaa
aaccb
shsudbud`;

const rows = input.split("\n").map(row => row);
rows.forEach(row => {
  const charArr = [...row];
  console.log(charArr);
});

In this snippet everything works fine. So here is where my questions start:

  1. Why does .filter() method not work properly in this case?
  2. Could this problem browser specific?

Thanks in advance.

  • Try using `trim()` ... `const rows = input.split("\n").map(row => row.trim());`. Not really clear if you are getting empty element(s) in array....or space at end of characters within rows – charlietfl Oct 19 '19 at 15:40
  • Maybe do a `console.log(btoa(await getData()))` and tell us what is printed. – Stratubas Oct 19 '19 at 17:42

0 Answers0