settingsAccountsettings
Menusettings

Q: Sum by Town - JavaScript task

+2 votes

You’re tasked with calculating the total sum of income for a number of Towns. You will receive an array of strings representing towns and their incomes, every even index will be a town and every odd index will be an income belonging to that town. Create an object that will hold all the towns as keys and their total income (the sum of their incomes) as values to those keys and print it as a JSON.

The input comes as an array of strings - each even index is the name of a town and each odd index is an income belonging to that town.

Examples:

Input:
Sofia
20
Varna
3
Sofia
5
Varna
4

Output:
{"Sofia":25,"Varna":7}


Input:
Sofia
20
Varna
3
sofia
5
varna
4

Output:
{"Sofia":20,"Varna":3,"sofia":5,"varna":4}


The output should be printed on the console - JSON representation of the object containing all towns and their total incomes.

asked in JavaScript category by user eiorgert

1 Answer

+1 vote

Here is the solution with the js code:

function sumByTown(input) {
    let sums = {};
    for (let i = 0; i < input.length; i+=2) {
        let [town, income] = [input[i], Number(input[i + 1])];
        if (sums[town] == undefined) {
            sums[town] = income;
        } else {
            sums[town] += income;
        }
    }
    console.log(JSON.stringify(sums));
}

sumByTown([
    "Sofia",
    "20",
    "Varna",
    "3",
    "Sofia",
    "5",
    "Varna",
    "4"
]);

 

answered by user hues
...