Skip to content Skip to sidebar Skip to footer

Javascript - Read Tab Delimited File, Line By Line Than Split Each Line Using Tab Delimited

I'm able to read a file line by line but I do not know how to split each lines using the tab delimited. here my code. Need some help on this issue ); lines.map(function(item){ var tabs = item.split('\t'); console.log("0",tabs[0], "1",tabs[1], "2",tabs[2],"3", tabs[3],"4", tabs[4], "5", tabs[5], "6", tabs[6]); arr1.push(tabs[0]); arr2.push(tabs[1]); arr3.push(tabs[2]); arr4.push(tabs[3]); arr5.push(tabs[4]); }); // test two of the arrays after reading:for (var i = 0; i < mdarr.length; i++) { console.log(arr1[i], arr2[i]); }; } reader.readAsText(file); };

Solution 2:

This can be done with a one liner. First split by new line then split by tab. The result is an 2d array where the first item is the header row.

const parsedString = tabbedString.split('\n').map((line) => line.split('\t'))

Example

const tabbedString = `Prefix    Name    Last Name   Email   Phone   Age Role
    Jim Loco    jilo@fox.com        32  Admin
Mrs.    Sara    Foo safoo@fox.com   124389  44  Admin
Mr. John    Deer    jodeer@fox.com      37  Developer`const parsedString = tabbedString.split('\n').map((line) => line.split('\t'))

console.log(parsedString)
[
  [
    "Prefix",
    "Name",
    "Last Name",
    "Email",
    "Phone",
    "Age",
    "Role"
  ],
  [
    "",
    "Jim",
    "Loco",
    "jilo@fox.com",
    "",
    "32",
    "Admin"
  ],
  [
    "Mrs.",
    "Sara",
    "Foo",
    "safoo@fox.com",
    "124389",
    "44",
    "Admin"
  ],
  [
    "Mr.",
    "John",
    "Deer",
    "jodeer@fox.com",
    "",
    "37",
    "Developer"
  ]
]

Note that stack overflow replaces tabs with 4 spaces so in the input string you will actually find 4 spaces and not a tab but in my original code they are indeed tabs.

Solution 3:

Here is how I converted a tab delimited file to a tree format in Node

var inputFile='Tree.tab'
fs = require('fs');

tree = {} 
fs.readFile(inputFile, 'ascii', function(err, data) {
    if(err) {
        console.log(err);
    }
    lines = data.split('\r\n');
    lines.map(function(line){
        levels = line.split("\t");
        if(typeof tree[levels[0]] === "undefined") {
           tree[levels[0]] = {}
        }
        node = tree[levels[0]]
        for ( var i = 1; i < levels.length; i++) {
            if(typeof node[levels[i]] === "undefined") {
                node[levels[i]] = {}
            }
        }

    });
    console.log(tree);
});

Post a Comment for "Javascript - Read Tab Delimited File, Line By Line Than Split Each Line Using Tab Delimited"