Chrissisbeast
Chrissisbeast

Reputation: 51

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);
}

this is the wanted result:

destination: {
  Bulgaria: { Sofia: 200, Sopot: 800 },
  France: { Paris: 2000 },
  Albania: { Tirana: 1000 }
}

and this is what I get:

destination: {
  Bulgaria: { Sofia: 500, Sopot: 800 },
  France: { Paris: 2000 },
  Albania: { Tirana: 1000 }
}

I get the bigger Sofia cost because its the last and it just overrides it, what I want is to get the lowest possible cost for Sofia.

Upvotes: 0

Views: 37

Answers (1)

trincot
trincot

Reputation: 350365

Add this line in your loop before you mutate destination:

    if (destination[country]?.[town] < cost) return;

It essentially checks whether there is already a cost for this town in your partial result, and if so, whether it is less than the cost you are currently processing. If that is true, then ignore this cost so you don't update the result with it.

Note that ?. is a rather new operator. Check the documentation on the optional chaining operator. In short, it here evaluates destination[country][town], except that it doesn't raise an exception when destination[country] is not defined, but instead propagates the undefined value to the end of the property chain.

Upvotes: 1

Related Questions