Home > front end >  How to make array from input
How to make array from input

Time:12-25

I have array in txt file and read this with

   fs.readFileSync("./input.txt")

When i wrap it in console.log i get(since it is written in the file itself):

    1 2 3 
    100 5000 

I would have the array:

['1','2','3','100','5000']

Placement of the array in the input file should not change. Suggest how to do it, please.

CodePudding user response:

You can use regex to split words: \w

let a = `    1 2 3 
    100 5000 `;
    
console.log(a.match(/\w /g))

To read your file and split it:

fs.readFileSync("./input.txt").match(/\w /g)

CodePudding user response:

One way, load it then, split by lines, then on each line split by space then flatten it, then filter out empty values.

let str = `1 2 3 
    100 5000 0`; // added 0 to show filter(Boolean) wont remove
    
console.log(str.split('\n').map(v => v.split(' ')).flat().filter(Boolean))

Result:

[
  "1",
  "2",
  "3",
  "100",
  "5000",
  "0"
]

CodePudding user response:

You could split the string by a space, then filter out the falsy items in the resulting array.

const input = `    1 2 3 
    100 5000 `;

let res = input.split(" ").filter(e => e.trim())
console.log(res)

  • Related