2017-02-20 28 views
0

我有兩個數組:如何篩選的陣列,以對應其它陣列

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"] 

WITHOUT使用字母或數字順序,因爲這將不會在這種情況下做的。

編輯: 羅素: 我怎麼這樣的標題排序:

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

回答

4

沒有兩個數組 - 有一個自定義類型的單個陣列,包含你需要

兩個變量

定義你的結構

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

,然後把它聲明

var dataArray : [MyCustomData] = [] 

填充它,然後在需要時對它進行排序 - 我已經按相反的順序填充只是這樣我們就可以使用zip保持兩個獨立的陣列同步的例子看到它正在排序

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)") 
+0

拉塞爾說什麼。 (投票)。試圖保持2個陣列同步是不必要的複雜。只需要一個包含所有需要的字段的單個數組,然後對該單個數組進行過濾/排序。 –

+0

如何訪問單個字符串,例如「1」? – Tuomax

+0

我已更新答案,以顯示您如何訪問個別字段 – Russell

0

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來獲取標題和類型的兩個單獨過濾數組。