Home > Net >  Sort and combine elements to be unique
Sort and combine elements to be unique

Time:04-30

I have a bunch of tokens stored in combinedCoinsFromAllWalles and I'm sorting them by who contains the largest monetary value like this:

let sortedCoins = combinedCoinsFromAllWalles.sorted() { Double($0.token!.quote!) > Double($1.token!.quote!) }

The problem is that some tokens are repeated by name, for example, on that sorting I could have 2 tokens with the same name on $0.token!.name

What would be the most efficient way to also combine those similar tokens and add their value? Something like this:

token A (named BTC)
token B (named BTC)
token C (named ETH)

I want to sum token A and B quote ($0.token!.quote! $0.token!.quote!) while filtering.

How do I do that in the most efficient way?

CodePudding user response:

That first sort in your example is a waste since you have not combined all the different sources for similar coins first and the order may then change.

You should:

  1. Aggregate coin values
  2. Sort by desired order

One simple way to do this would be to create a dictionary, adding new coins or summing totals as you iterate through your data. Then convert the dictionary back to an array and sort how you would like.

Ex:

var dict: [String: Float] = []
for each in combinedCoinsFromAllWalles {
    if dict.contains(each.token) {
        dict[each.token]  = each.quote
    }else{
        dict[each.token] = each.quote
    }
}

let sortedCoinValueArray = dict.sorted(by: $0.1 < $1.1)

The resulting array is an array of key-value pairs, so you may iterate over it like this:

for (key, value) in sortedCoinValueArray {
    print("${key}:   ${value}"
}
  • Related