Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I filter a 2d array in Swift?

I'm trying to filter data from 2d array according to the string/text which is entered by user like if we write the name or phone number of a person it contact detail is searched and shown.

In 2D array [["Name","Phone number"]]. if number or name which is entered by the user is matched with any value then that will store in an other array.

var data : [[String]] = [["AB","+923476760226"],["Umair","+923366111830"],.......]
like image 682
Abdul Rehman Avatar asked Sep 14 '25 22:09

Abdul Rehman


1 Answers

The way to filter a 2D array is to filter twice, once per level.

var data = [["AB","+923476760226"],["Umair","+923366111830"]]
let searchString = "+9234"

var result = data.filter { (dataArray:[String]) -> Bool in
    return dataArray.filter({ (string) -> Bool in
        return string.containsString(searchString)
    }).count > 0
}

This code just filters out all the items that has at least one item that contains the searchString.

However, I'd like to say that you really should keep the name and number in a separate class or struct and build some mach function so that you don't have to filter twice

struct Contact{
    let name: String
    let number: String

    init(name: String, number:String) {
        self.name = name
        self.number = number
    }

    func match(string:String) -> Bool {
        return name.containsString(string) || number.containsString(string)
    }
}


let properData = [Contact(name: "AB", number: "+923476760226"), Contact(name: "Umair", number: "+923366111830")]

let properResult = properData.filter { (contact) -> Bool in
    return contact.match(searchString)
}

This will make your code a bit cleaner in the long run and it's a good idea to work with classes and struct like this in general

like image 168
Moriya Avatar answered Sep 16 '25 11:09

Moriya