1

I'm writing a program that gives me random song names I've input into a text file. Here's the code I have so far:

var fs = require('fs'),
    path = require('path');

fs.readFile('names.txt', 'utf8', function(err, data) {
    var arr = data.toString().split('\n'),
        names = [];
    for (var i in arr) {
        if (arr[i].length !== 0) {
            names.push(arr[i].trim());
        }

    }


    console.log(names[1]);
});

I've noticed that whenever I put an odd number into the console.log() statement it returns the empty newline / whitespace. How can I fix this or remove it? Thanks for any help!

DevonAero
  • 65
  • 1
  • 6

2 Answers2

2

Your situation isn't entirely clear without full details, mainly the contents of the text file, but you probably meant to trim before the if.

Try like this:

for (var i in arr) {
        var trimmed = arr[i].trim();
        if (trimmed .length !== 0) {
            names.push(trimmed);
        }

}

Also, you shouldn't really for(.. in ..) in arrays (See here).

It's better if you use for(var i = 0; i < arr.length; i++) (you can keep the rest exactly as it is)

Community
  • 1
  • 1
Amit
  • 43,881
  • 8
  • 73
  • 106
1

Alternatively:

var names = data.toString().split('\n').map(function(line){
    return line.trim();
}).filter(Boolean);
loganfsmyth
  • 146,797
  • 27
  • 317
  • 241
  • Looks good, it's amazing how many different ways you can solves problems in programming. Thanks so much! – DevonAero Jul 26 '15 at 15:27