0

How can I find a specific item from custom object in a huge array like bellow?

struct ResponseCourseTypeFilter {
    var returnCourseTypeFilter: [[String : String]]
}

struct ViewModelCourseTypeFilter {
    struct DisplayedCourseTypeFilter {
        var titlesCourseType: String
        var isSelectedType: Bool
    }
    var displayedCourseTypeFilter: [DisplayedCourseTypeFilter]
}

I need to get values titlesCourseType are true.

My array is huge.

6
  • Do you need to filter an array of type CourseTypeFilter Commented Nov 4, 2019 at 9:13
  • I can't find the array example, but I guess your array is an array of CourseTypeFilter. array.first(where: { $0. isSelectedType == true }) this is if you need only one item, and array.filter { $0. isSelectedType == true } for all of them. Google magic Commented Nov 4, 2019 at 9:14
  • @ Sh_Khan. I need to get values titlesCourseType are true. Commented Nov 4, 2019 at 9:15
  • titlesCourseType is a string, did you mean the property isSelectedType? And do you want to filter the array displayedCourseTypeFilter or some other array? Commented Nov 4, 2019 at 9:38
  • How huge is your array, thousands , or millions? Commented Nov 4, 2019 at 9:39

2 Answers 2

1

If suppose the ViewModelCourseTypeFilter instance is like,

let viewModel = ViewModelCourseTypeFilter(displayedCourseTypeFilter: [
    DisplayedCourseTypeFilter(titlesCourseType: "First", isSelectedType: true),
    DisplayedCourseTypeFilter(titlesCourseType: "Second", isSelectedType: false),
    DisplayedCourseTypeFilter(titlesCourseType: "Third", isSelectedType: true)
])

Then you can get all titlesCourseType values where isSelectedType = true like so,

let arr = viewModel.displayedCourseTypeFilter.compactMap({ $0.isSelectedType ? $0.titlesCourseType : nil })
print(arr) //["First", "Third"]
Sign up to request clarification or add additional context in comments.

1 Comment

@ PGDev. Is it work for huge arrays? for example 10000 items.
0

use

let arr = viewModel.displayedCourseTypeFilter.filter { $0.isSelectedType }

better?

2 Comments

Code-only answers are generally frowned upon on this site. Could you please edit your answer to include some comments or explanation of your code? Explanations should answer questions like: What does it do? How does it do it? Where does it go? How does it solve OP's problem? See: How to anwser. Thanks!
Oh, yeah, I am trying to do better.

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.