Tuomax
Tuomax

Reputation: 31

How to filter an array to correspond other array

I've two arrays:

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

I filter the first array as a part of using searchbar. The order of the elements might change completely. However, I can't filter the second array the same way I did the first one, because I don't want to take it in to count when searching. But I would like for the second array to be in the same order as the first one. So, to recap. How can I filter an array to match another one by indexes perfectly?

An example:

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 using alphabetical or numerical order, as that won't do in this case.

EDIT: TO Russell: How do I sort the titles like this:

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

Upvotes: 0

Views: 121

Answers (2)

Russell
Russell

Reputation: 5554

don't have two arrays - have a single array of a custom type, containing both variables that you need

Define your struct

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

and then declare it

var dataArray : [MyCustomData] = []

populate it and sort it where required - I have populated in reverse order just so that we can see it being sorted

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

Upvotes: 4

BallpointBen
BallpointBen

Reputation: 13999

An example of keeping two separate arrays in sync using 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 })

You can use map on the filtered result to get back two separate filtered arrays for the titles and types.

Upvotes: 0

Related Questions