DEV Community

Srinivas Kandukuri
Srinivas Kandukuri

Posted on

Node Js Interview Question(Read a file, filter with date range, sort by field)

Note : below 3 question and answers are continuous

Input filename : test.txt

foo,12,2019-01-02,2019-03-03,200
bar,30,2019-03-08,2019-05-01,100
jar,1,2019-01-04,2019-03-03,200
mar,56,2018-02-05,2018-05-01,10
Enter fullscreen mode Exit fullscreen mode

Question #1

Read a text file with comma separated values.

Answer

let fs = require('fs');
let data = fs.readFileSync('test.txt','utf8');
let rows = data.split('\n');
let array =  rows.map( eachrow => {
    let row = eachrow.split(",");
    return row;
})
Enter fullscreen mode Exit fullscreen mode

Question #2

Select data between rage of dates in given file

let result = array.filter(obj => {
    let first = new Date('2019-01-01');
    let last = new Date('2019-05-30');
    return (new Date(obj['2']) > first && new Date('2') < last);
});
Enter fullscreen mode Exit fullscreen mode

Question #3

Sort based on names and print the result

function compare(a,b){
    if(a[0] ==  b[0]){
        return 0;
    }
    else{
        return (a[0] < b[0]) ? -1 : 1;
    }
}
result.sort(compare);
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)