【问题标题】:How to filter an array to correspond other array如何过滤一个数组以对应其他数组
【发布时间】:2017-02-21 01:25:27
【问题描述】:

我有两个数组:

var filteredTitles = [String]()
var filteredTypes = [String]()

我过滤第一个数组作为使用搜索栏的一部分。元素的顺序可能会完全改变。但是,我无法像第一个数组一样过滤第二个数组,因为我不想在搜索时将其计算在内。但我希望第二个数组与第一个数组的顺序相同。所以,回顾一下。如何通过索引过滤一个数组以完美匹配另一个数组?

一个例子:

var filteredArray = ["One", "Two", "Three"]
//Sort the below array to ["1", "2", "3"], the order of the upper array
var toBeFilteredArray = ["2", "1", "3"]

不使用字母或数字顺序,因为在这种情况下不会这样做。

编辑: 致拉塞尔: 如何像这样对标题进行排序:

// When there is no text, filteredData is the same as the original data
    // When user has entered text into the search box
    // Use the filter method to iterate over all items in the data array
    // For each item, return true if the item should be included and false if the
    // item should NOT be included
    searchActive = true
    filteredData = searchText.isEmpty ? original : original.filter({(dataString: String) -> Bool in
        // If dataItem matches the searchText, return true to include it
        return dataString.range(of: searchText, options: .caseInsensitive) != nil
    })

【问题讨论】:

    标签: arrays swift filtering


    【解决方案1】:

    没有两个数组 - 有一个自定义类型的数组,包含您需要的两个变量

    定义你的结构

    struct MyCustomData
    {
        var dataTitle   : String = ""
        var dataType    : String = ""
    }
    

    然后声明它

    var dataArray : [MyCustomData] = []
    

    填充它并在需要的地方对其进行排序 - 我以相反的顺序填充它,以便我们可以看到它正在排序

    dataArray.append(MyCustomData(dataTitle: "Third", dataType: "3"))
    dataArray.append(MyCustomData(dataTitle: "Second", dataType: "2"))    
    dataArray.append(MyCustomData(dataTitle: "First", dataType: "1"))
    
    let filteredArray = dataArray.sorted {$0.dataTitle < $1.dataTitle}
    for filteredElement in filteredArray
    {
        print("\(filteredElement.dataTitle), \(filteredElement.dataType)")
    }
    // or, to print a specific entry
    print("\(filteredArray[0].dataTitle), \(filteredArray[0].dataType)")
    

    【讨论】:

    • 罗素说过的话。 (已投票。)试图保持 2 个数组同步是不必要的复杂。只需拥有一个包含您需要的所有字段的数组,然后对该数组进行过滤/排序。
    • 如何访问单个字符串,例如“1”?
    • 我已更新答案以显示您如何访问各个字段
    • 我将如何在下面使用它?:
    【解决方案2】:

    使用zip 保持两个独立数组同步的示例:

    let titles = ["title1", "title3", "title4", "title2"]
    let types = ["typeA", "typeB", "typeC", "typeD"]
    
    let zipped = zip(titles, types)
    
    // prints [("title4", "typeC"), ("title2", "typeD")]
    print(zipped.filter { Int(String($0.0.characters.last!))! % 2 == 0 })
    

    您可以在过滤后的结果上使用map 来获取标题和类型的两个单独的过滤数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 2021-03-21
      • 2017-02-07
      • 1970-01-01
      • 2013-10-08
      • 2020-10-17
      相关资源
      最近更新 更多