0

So I have a short question: I'm reading data from a file, that works. I'm adding these data to a string, that's ok.

But when it comes to comparing these data on an if-statement it doesn't simply become true.

I've done console.log of the string, and it appears correct:

["A", "B", "C", "D", "E"]

I've tried to rewrite the data, I've checked for syntax errors on the text file, but everything looks correct.

for (var i = 0; i < lineArray.length; i++) {
        var singleLine= lineArray[i].split(' ');
        console.log(singleLine) //And I get the array ["A", "B", "C", "D", "E"]
          if (singleLine[4] === 'E') {
             console.log("it works")
   }
}

The thing I'm expecting to happen is to get the 'it works' on the console.

MZ97
  • 201
  • 1
  • 11
  • There must be something else there in `singleLine[4]`. Have you tried adding `console.log(singleLine[4].length)`? – Pointy Jun 08 '19 at 11:51
  • Since you are reading from a file - could it be the encoding thats causing the inequality? – BroBan Jun 08 '19 at 11:53
  • Add what object you are getting as singleLine, not console log but actual object – Ganesh Karewad Jun 08 '19 at 11:54
  • Unrelated to your problem, you should use let/const rather than var if you can. – jarmod Jun 08 '19 at 11:55
  • What is `lineArray` and `lineArr`? Please provide input examples. – Hensler Software Jun 08 '19 at 11:58
  • You can console.log(singleLine[4], 'E') to see if there's a difference – Avin Kavish Jun 08 '19 at 12:09
  • @Pointy sorry for late reply! The length of the elements are always +1 for the last element on the line. For example the length of the 'E' is 2. – MZ97 Jun 17 '19 at 13:25
  • @MZ97 well that means there's some additional character in the string. You can use `.charCodeAt()` to check the Unicode numeric value for each part of the string. – Pointy Jun 17 '19 at 13:30
  • @BroBan I think every last element on every line is having a kind of new-line (\n), but that is invisible. I have tried to compare it with 'E\n' or 'E \n'. But no success – MZ97 Jun 17 '19 at 13:34
  • @Pointy I get that the second char is 13. Any idea what that is? – MZ97 Jun 17 '19 at 13:37
  • That's a "carriage return" character, picked up from the original file probably. – Pointy Jun 17 '19 at 13:39
  • @Pointy Thank you so much for your help! The solution was to compare it with 'E\r'. I'll soon be answering the question on my own here. – MZ97 Jun 17 '19 at 13:42

2 Answers2

0
let lineArray = ["A", "B", "C", "D", "E"];

lineArray.forEach(a => {
        console.log(a); 
    if (a ==="E") console.log("its work")
    })
0

The problem on this case was the invisible 'Carriage Return' or '\r' on every last element of every line.

The solution on my case was to compare the letter E with 'E\r'. This will result on the if-statement to be true.

MZ97
  • 201
  • 1
  • 11