-1

i have text file, with this pattern. list of number that were separated with enter or \n. at end of file there is lot of enter

1
2
3



... //my main is enter

when i read this file whit this code and log the contents, output is and typeof is string:

var contents = fs.readFileSync('./myFile', 'utf8');

1
2
3



...

then i would like this data split with \n and convert this string to array. using this code. but finally answer is : contents.split("\n") have data : [1, 2, 3, '', '', '', '']

var listOfNationalCode = contents.split("\n").map(function (n) {
        if (n != '') {
            return n;
        }
    }); 
console.log(listOfNationalCode);

[ '1',
  '2',
  '3',
  undefined,
  undefined,
  undefined,
  undefined ]

What should I do now for not return undefined in this code? and i have [1, 2, 3]

mohammad javad ahmadi
  • 2,031
  • 1
  • 10
  • 27
  • 4
    `if (n != '') { return n; }` returns `n` if it's not an empty string **or undefined otherwise**. All functions implicitly return `undefined` if there is no other `return`. Moreover, mapping is a 1:1 operation - each member of the original array results in one mapped value. You are probably looking for `Array#filter`. – VLAZ Oct 15 '19 at 07:54
  • 1
    Use `.trim()` before `.split()`: `contents.trim().split("\n")...` – Yevhen Horbunkov Oct 15 '19 at 07:57
  • @VLAZ: since your comment is actually the answer, why not to post it as such? It became common on SO to have comments much more useful than answers, which is painful, because comments are hard to read and not googleable. – georg Oct 15 '19 at 07:58
  • @georg I've been searching for a good dupe target. This isn't a new problem, after all. I don't think we need literally hundreds of answers that are basically "this is how `map` works and how `filter` works". – VLAZ Oct 15 '19 at 08:00
  • @VLAZ, your comment is help full foe me. – mohammad javad ahmadi Oct 15 '19 at 08:01

3 Answers3

0

try this

let l=[1, 2, 3, '', '', '', ''].filter(function (n) {
        if (n != '') {
            return n;
        }
    }); 
console.log(l);
Sudhakar
  • 533
  • 1
  • 3
  • 17
  • 1
    no need for an `if` - just return `n != ''`. Even `return n` would work, since an empty string is falsey. Going further, you don't even need a custom function - `.filter(Boolean)` is enough. – VLAZ Oct 15 '19 at 07:57
0

Like said in the comment, mapping is a 1:1 operation so you can't return resaults for only some of the values.

use the Array.filter() method instead:

var listOfNationalCode = contents.split("\n").filter( n => n != '' ); 
console.log(listOfNationalCode);
Gibor
  • 1,695
  • 6
  • 20
-1

You can try this:

var listOfNationalCode = [];
contents.split("\n").map(function (n) {
    if (n != '') {
        listOfNationalCode.push(n)
    }
}); 
console.log(listOfNationalCode);
Dino
  • 7,779
  • 12
  • 46
  • 85
Javad Khodadadi
  • 410
  • 1
  • 4
  • 13