0

I have just started learning node.js. I am trying to create a script that will get a list from a file. The list is built like this

Bob:110
Mike:120
Bob:334
Dan:240

And will give this output

name value

It is supposed to sum the numbers associated with the same name.

So in my example it would print

Bob 444
Mike 120
Dan 240

I used the help I found in this site to create some basic script

fs = require('fs');
var array = fs.readFileSync('C:\\data.txt').toString().split("\n");

var items = {}, base, key;
for (var i = 0; i < array.length; i++) {
    base = array[i];
    key = base[0];
    if (!items[key]) {
        items[key] = 0;
    }
    items[key] += base[1];
}

var outputArr = [], temp;
for (key in items) {
    temp = [key, items[key]]
    outputArr.push(temp);
}
console.log(outputArr);

Notice that I get the list from a text file, but it currently contains what I have posted in this question. The output that I get is very gibberishy, and I am not sure why. This is my output:

[ [ 'B', '0oo' ],
  [ 'M', '0i' ],
  [ 'D', '0a' ],
  [ 'undefined', NaN ] ]

Can anyone please help me understand why this does not work properly and show me how to fix it?

By the way, I am not certain if this is the correct thought line for accomplishing such a task in node.js. I would be happy to get feedback!

Thanks a lot!

3
  • @DLeh It is considered bad etiquette to suggest a solution using a framework or library that is not tagged or labeled in the original question. Commented Apr 7, 2015 at 20:13
  • @DavidL yes, i agree. however the top answer in this question included a vanilla js solution. i linked directly to that answer in the duplicate but it converted to just the question link. Commented Apr 7, 2015 at 20:14
  • @DLeh ah, fair enough. If the link to answer hadn't been swallowed that would have vastly clearer. I concur with your close vote. Commented Apr 7, 2015 at 20:15

1 Answer 1

1

Well, you could use a function to satisfy your needs:

function PrintAllValuesInList(name,list){
     var values = [];
     for (var i = 0 ; i < list.length ; i++){
        if (list[i].name == name)
           values.push(list[i].value);
     }
     console.log("Name ",name, " Values ", values.join());       
  }

And a call to that would be:

var arr = [{ name: 'x', value: 'a'},
           { name: 'y', value: 'b'},
           { name: 'x', value: 'c'},
           { name: 'z', value: 'd'}];

PrintAllValuesInList('x',arr);

Would output:

Name  x  Values  a,c

Here is the plunker: Plunker

Thanks if i could help.

Sign up to request clarification or add additional context in comments.

2 Comments

You might want to move the console log inside of the function :)
Sorry i was creating and posted it before it was ready. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.