1

I have multiple arrays in a data model. I would like to take an array from each of the data models and concatenate them, then delete the duplicate strings in the array. Is this possible? I'm sure I can work out how to delete the duplicates after but I am struggling to concatenate them first.

My data model (I am trying to concatenate the application array) :

let productData: [ProductModel] = [
    ProductModel(
        title: "option1",
        application: ["Food","Agriculture","Gin","Metals","Poylmers"]
    ),
    ProductModel(
        title: "option2",
        application: ["Food","Agriculture","Gin", "Polymers"]
    ),
    ProductModel(
        title: "option3",
        application: ["Food","Metals","Poylmers"]
    ),
    ProductModel(
        title: "option4",
        application: ["Gin","Metals","Poylmers"]
    ),
]

Here is where I am trying to append the array but I all I seem to be doing is adding an empty string to each of the arrays:

let applicationItems = products.filter { product in
    let list = product.application
    var collectedList = [""]
    for item in list {
        collectedList.append(contentsOf: list)
        return true
    }
    return false
}

2 Answers 2

3

Use flatMap and add the result to a Set to only get unique values

let applications = Array(Set(productData.flatMap(\.application)))
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to concatenate all the strings from the application arrays in a single array you can use flatMap as below:

 let concatenatedArray = productData.flatMap({$0.application})

And if you want to concatenate strings into an array of strings array you can use map as below:

 let concatenatedArray = productData.map({$0.application})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.