How to sort object’s values to be the lowest possible

we have example input which is:

solve2([
    "Bulgaria > Sofia > 200",
    "Bulgaria > Sopot > 800",
    "France > Paris > 2000",
    "Albania > Tirana > 1000",
    "Bulgaria > Sofia > 500"
    ])

I basicly add them to an object like that:

destination= {
bulgaria: {Sofia: 500, Sopot: 800},
france: {Paris: 2000}
//and the rest the same way
}

So the example gives us: country > town > cost And I want to take the for example if there are 2 Sofias I want to take the one with the lower cost, but the code I will give you down just overrides them.

function solve2(input)
{
    let destination = {};

    input.forEach(set => {
        let [country, town, cost] = set.split(' > ');
        cost = Number(cost)

        destination[country] = {
            ...destination[country],
            [town]: cost
        };
        
    });

   console.log(destination);
}

I want when there are 2 towns in the same country to take the lower cost and put it in the object of destination and then in Bulgaria and the bigger cost just to be skipped.



Read more here: https://stackoverflow.com/questions/64958465/how-to-sort-objects-values-to-be-the-lowest-possible

Content Attribution

This content was originally published by Chrissisbeast at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: