Home > OS >  Multiple sort with Alpabet and count swift
Multiple sort with Alpabet and count swift

Time:01-11

i have to to a multiple sort of Array, but it doesnot work

This is expected output. now this array is mixed up

struct Variant {
    var name: String
    var count: Int
}


let array = [
    Variant(name: "Ab", count: 12),
    Variant(name: "Ac", count: 10),
    Variant(name: "Ad", count: 8),
    Variant(name: "Ae", count: 0)
    Variant(name: "Bc", count: 55),
    Variant(name: "Bd", count: 45)]

i try do it like this, but it make priority on count and doesnot care about name

array = array.sorted(by: {
    ($0.count ?? 0, $1.name) > ($1.count ?? 0, $0.name)
})

CodePudding user response:

Tuple comparison is a good approach to sort elements by multiple criteria, but you got the order of the tuple elements wrong.

The tuples are compared in “lexicographic order,” starting with the first (leftmost) element. In order to sort by name first, $0.name resp. $1.name must be the first tuple elements.

Therefore for ordering by name (ascending) first, and by count (descending) second, the sort function should be

array.sorted(by: {
    ($0.name, $1.count) < ($1.name, $0.count)
})

CodePudding user response:

To sort based on multiple criteria, just include the conditions cascading each other based on priority.

EDIT: Thanks to Martin R pointing out the error, here's the revised code:

array.sorted(by: {
    //First layer of filter. Sorts based on alphabetic order
    if $0.name < $1.name {
        return true
    }
    else if $0.name > $1.name {
        return false
    }
    //Second layer. Sorts based on greater count
    return $0.count > $1.count
})

Input:

let array = [
    Variant(name: "Bd", count: 55),
    Variant(name: "Bc", count: 55),
    Variant(name: "Ac", count: 12),
    Variant(name: "Ab", count: 12),
    Variant(name: "Ad", count: 8),
    ]

After sort:

Variant(name: "Ab", count: 12),
Variant(name: "Ac", count: 12),
Variant(name: "Ad", count: 8),
Variant(name: "Bc", count: 55), 
Variant(name: "Bd", count: 55)
  • Related