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

Q: Heroic Inventory - JavaScript task

+4 votes

In the era of heroes, every hero has his own items which make him unique. Create a function which creates a register for the heroes, with their names, level, and items, if they have such. The register should accept data in a specified format, and return it presented in a specified format.

The input comes as array of strings. Each element holds data for a hero, in the following format:
“{heroName} / {heroLevel} / {item1}, {item2}, {item3}...”

You must store the data about every hero. The name is a string, the level is a number and the items are all strings.

Examples:

Input:
Isacc / 25 / Apple, GravityGun
Derek / 12 / BarrelVest, DestructionSword
Hes / 1 / Desolator, Sentinel, Antara

Output:
[{"name":"Isacc","level":25,"items":["Apple","GravityGun"]},{"name":"Derek","level":12,"items":["BarrelVest","DestructionSword"]},{"name":"Hes","level":1,"items":["Desolator","Sentinel","Antara"]}]


Input:
Jake / 1000 / Gauss, HolidayGrenade

Output:
[{"name":"Jake","level":1000,"items":["Gauss","HolidayGrenade"]}]


The output is a JSON representation of the data for all the heroes you’ve stored. The data must be an array of all the heroes. Check the examples above for more info.

asked in JavaScript category by user mitko

1 Answer

+3 votes

Here is my solution:

function heroicInventory(dataRows) {

    let heroData = [];
    for (let i = 0; i < dataRows.length; i++) {
        let currentHeroEl = dataRows[i].split(" / ");

        let currentHeroName = currentHeroEl[0];
        let currentHeroLevel = Number(currentHeroEl[1]);

        let currentHeroItems = [];
        if (currentHeroEl.length > 2) {
            currentHeroItems = currentHeroEl[2].split(", ");
        }

        let hero = {
            name: currentHeroName,
            level: currentHeroLevel,
            items: currentHeroItems
        };
        heroData.push(hero);
    }
    console.log(JSON.stringify(heroData));
}

heroicInventory([
    "Isacc / 25 / Apple, GravityGun",
    "Derek / 12 / BarrelVest, DestructionSword",
    "Hes / 1 / Desolator, Sentinel, Antara"
]);

 

answered by user nikole
...