settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Aggregate Table - list of towns in JavaScript

+1 vote

You will be given a list of towns and incomes for each town, formatted in a table, separated by pipes (|). Write a JavaScript function that extracts the names of all towns and produces a sum of the incomes. Note that splitting may result in empty string elements and the number of spaces may be different in every table.

The input comes as array of string elements. Each element is one row in a formatted table.

Examples:

Input:
['| Sofia           | 300',
 '| Veliko Tarnovo  | 500',
 '| Yambol          | 275']

Output:
Sofia, Veliko Tarnovo, Yambol
1075

The output is printed on the console on two lines. On the first line, print a comma-separated list of all towns and on the second, the sum of all incomes.

asked in JavaScript category by user golearnweb

1 Answer

+1 vote

Here is the javascript code:

function table(lines) {

    let sum = 0;
    let list = [];

    for (let line of lines) {
        let townData = line.split("|");
        let townName = townData[1].trim();
        let income = Number(townData[2].trim());
        list.push(townName);
        sum += income;
    }
    console.log(list.join(", ") + "\n" + sum);
}

table(['| Sofia           | 300',
        '| Veliko Tarnovo  | 500',
        '| Yambol          | 275']
);

 

answered by user john7
...