如何使用地图和过滤器从一维数组生成二维数组?

时间:2018-10-08 13:16:15

标签: ios arrays swift multidimensional-array higher-order-functions

我今天使用循环获得了所需的输出,但是如何使用map和filter与单行表达式交换该循环呢?

我从许多国家入手。根据这一点,我使用map生成了第二个带有首字母的数组。现在,我想使用map和filter建立一个二维数组,在单独的数组中包含所有具有相同首字母的国家,这样我就可以摆脱今天使用​​的循环。

let countries = ["Albania", "Algeria", "Angola", "Bahamas", "Bahrain", "Canada"]

var initials = Set(countries.map { $0.prefix(1) }).sorted()

func countriesByInitial() -> [[String]] {
    var result = [[String]]()
    for initial in initials {
        result.append(countries.filter { $0.prefix(1) == initial })
    }
    return result
}

3 个答案:

答案 0 :(得分:3)

您可以通过以下方式实现 group> sort> map 组合:

let countries = ["Algeria", "Albania", "Belarus", "Bahamas", "Canada"]
let groupedDict = Dictionary(grouping: countries, by: { $0.prefix(1) })
let sortedDict = groupedDict.sorted(by: { $0.key < $1.key })
let arr2D = sortedDict.map({ $0.value })

您可以将其写成一行:

let arr = (Dictionary(grouping: countries, by: { $0.prefix(1) })).sorted(by: { $0.key < $1.key }).map({ $0.value })

您还可以在数组上使用reduce:

// $ 0的类型为[[String]]

// $ 1的类型为String

let arr2D: [[String]] = countries.reduce(into: []) {
    let checkChar = $1.first
    if let idx = $0.index(where: {$0.first?.first == checkChar }) {
        $0[idx].append($1)
    } else {
        $0.append([$1])
    }
}

答案 1 :(得分:3)

如果数组已经排序,则可以使用Swift 4方法reduce(into:),否则,在对它进行分组之前,只需对其进行排序:

let countries = ["Albania", "Algeria", "Angola", "Bahamas", "Bahrain", "Canada"]

let grouped: [[String]] = countries.reduce(into: []) {
    if $0.last?.last?.prefix(1) == $1.prefix(1) {
        $0[$0.index(before: $0.endIndex)].append($1)
    } else {
        $0.append([$1])
    }
}

print(grouped)   // [["Albania", "Algeria", "Angola"], ["Bahamas", "Bahrain"], ["Canada"]]\n"

答案 2 :(得分:1)

您可以映射将通过过滤 apiVersion: v1 kind: Pod metadata: name: cas-de namespace: ds-svc spec: containers: - name: ds-mg-cas image: "docker-all.xxx.net/library/ds-mg-cas:latest" imagePullPolicy: Always ports: - containerPort: 8443 - containerPort: 6402 env: - name: JAVA_APP_CONFIGS value: "/apps/ds-cas/configs" - name: JAVA_EXTRA_PARAMS value: "-Djava.security.auth.login.config=./config/jaas.config -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=6402" volumeMounts: - name: ds-cas-config mountPath: "/apps/ds-cas/context" volumes: - name: ds-cas-config hostPath: path: "/apps/ds-cas/context" 字符串的首字母设置的initial设置为:

countries

因此,let countries = ["Albania", "Algeria", "Angola", "Bahamas", "Bahrain", "Canada"] var initials = Set(countries.map { $0.prefix(1) }).sorted() let array = initials.map { letter -> [String] in return countries.filter { $0.prefix(1) == letter } } 是一个字符串数组(array)的数组,如下:

  

[[[“阿尔巴尼亚”,“阿尔及利亚”,“安哥拉”],[“巴哈马”,“巴林”],[“加拿大”]]