1

I have a text file:

2|BATH BENCH|19.00
20312100000|ORANGE BELL|1.42
04525514840|BOILER ONION|1.78

I need to find the summation of the price which is (19.00,1.42,1.78) and print it in the console.

var FilePath = process.argv[2];
var allUpcs = [];
var subtotal = 0;

const fs = require('fs');
const readline = require('readline');

const file = readline.createInterface({
input: fs.createReadStream(FilePath),
output: process.stdout,
terminal: false
});

file.on('line', (line) => {
allUpcs.push(line.split('|')[2]).map(Number);

var subtotal = allUpcs.reduce(function(pv, cv) { return pv + cv; }, 0);
});

file.on('close', function() {
console.log(subtotal = allUpcs.reduce(function(pv, cv) { return pv + cv; }, 0));
});

I am not getting the correct output, getting it as Subtotal 019.001.421.78.

Can anyone please help? Thanks.

2
  • 1
    You should be getting errors because of allUpcs.push(line.split('|')[2]).map(Number); the push() method returns a number (the new length of the array), so there is no .map() method on it. Commented Feb 2, 2021 at 22:22
  • The subtotal calculations in the line event handler are not being used. You can remove them. Only the one in the close handler matters. Commented Feb 2, 2021 at 22:25

1 Answer 1

1

You're not using the result of the map anywhere, so you're still just pushing a string into the array, then discarding the result of map.

Use this instead:

allUpcs.push(parseFloat(line.split('|')[2]));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.