Home > Software engineering >  Function to split a string twice in javascript and sum the total marks
Function to split a string twice in javascript and sum the total marks

Time:09-05

I am new to javascript and trying to write a function to calculate the total marks. I have some input text that i need to clean/split.

Example:

a, 80newlineb, 50newline

The output of the first array after splitting on 'newline' should be something like this:

["a, 80" , "b, 50"]

I'm then trying to loop through and create an additional array in a format from which i can calculate the total marks. Something like this:

function getTotal(input_text)
{
    const lines = input_text.split("newline");
    var arrayLength = lines.length;

    marks_array = [];

    for(var i=0; i<arrayLength; i  ){
        lines[i].split(",");
        split = {module:lines[0], mark:lines[1]};
        module_marks.push(split);
    }

    some code

    return total_marks;
}

I've only ever really used php and think i am merging two languages into one and getting confused. Any help would be much appreciated!

EDIT In this example the answer should be 130.

CodePudding user response:

After splitting on the newline, filter out empty results, then split again on a comma and space. (not just on a comma, since you want only the numeric part on the right, not a number with a leading space.) That'll give you the first result you're looking for. Then, with that, map to the second item in each - the numeric part - and add them all up with .reduce.

const input = `a, 80newlineb, 50newline`;
const lines = input
  .split('newline')
  .filter(Boolean) // remove empty lines
  .map(line => line.split(', '));
console.log(lines);
const sum = lines
  .map(line => line[1])
  .reduce((a, b) => a   Number(b), 0);
console.log(sum);

CodePudding user response:

There are a number of ways you can achieve this. If all you need is the total match on the digits with a regular expression to get an array of numbers, and then iterate over that array adding the numbers to a new variable.

Note: the numbers you extract from the string will also be strings, so you have to coerce them to a number. You could map over the array with .map(Number) to return a new array of integers, prefix the number before adding it to the total ( number), or use the Number constructor. This example uses the prefix method.

Note 2: I've deliberately missed out the part where you want ['a, 80' , 'b, 50'] as output because it's not clear whether it was just a stepping stone to your final result, or whether you we going to use it for something else. If it's the latter you may want to think about using an object to structure that data instead.

const str = 'a, 80\nb, 50\n';
const numbers = str.match(/\d /g);

let total = 0;

for (const number of numbers) {
  total  =  number;
}

console.log(total);

CodePudding user response:

You can split the string by the \n and by the , at once using a regular expression.
And then use reduce to add the numbers to a total if those are not NaN or empty strings.

const inputText = "a, 80\nb, 50\n";

const getTotal = (text) =>
  text.split(/[\n|,]/).reduce((total, item) => {
    return isNaN(item) || item === "" ? total : total   parseInt(item);
  }, 0);

console.log(getTotal(inputText));

  • Related