简体   繁体   中英

Filtering the inputs in Node.js

Here, I am fetching a data from the user. The first line contains an integer, denoting the number of entries in the phone book. Each of the subsequent lines describes an entry in the form of space-separated values on a single line. The first value is a friend's name , and the second value is a digit phone number .

For example:

2
sam 99912222
tom 11122222

So, while processing this input, I am taking the number of entries from the user and assigning it to variable noOfIterations . For the subsequent entries, I am assigning it to a list of objects wherein the format will be : for eg. [{ sam: '99912222' },{ tom: '11122222' }] .

But the problem is I get [ 'sam 99912222', 'tom 11122222' ] instead while consoling the map variable. Why do I get this?

function processData(input) {
    var noOfIterations = 0;
     var map = input.split('\n').filter(function (string, index){
        if(index===0){
            noOfIterations = parseInt(string);
        }
        else{
            var splitStrings = string.trim().split(' ');
            var obj = {};
            obj[splitStrings[0]] =  splitStrings[1];
            console.log(obj);
            return obj;
        } 
     });
     console.log(map);
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

You need to use map instead of filter to transform the input data.

function processPhoneBook(input) {
    var result = input.split('\n')
        .filter(function(line, index) { return index > 0 })
        .map(function(line) {
            var splitLine = line.trim().split(' ');
            return {[splitLine[0]]: splitLine[1]};
        });

    console.log(result);
}

Example: processPhoneBook("3\\nana 1\\npep 2") outputs [ { ana: '1' }, { pep: '2' } ]

I've removed noOfIterations var since you weren't using it. If you need to use it for further processing, you can filter the result after the mapping phase:

function processPhoneBook(input) {
    var noOfIterations = 0;
    var result = input.split('\n')
        .map(function(line, index) {
            if (index === 0) {
                noOfIterations = parseInt(line);
                return null;
            }
            var splitLine = line.trim().split(' ');
            return {[splitLine[0]]: splitLine[1]};
        })
        .filter(function(line) { return line != null })

    console.log(result);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM