2

is there any way to get list of filtered indexes instead of objects.

class Object
{
 var name
 var goal
}

var array<Object> = Array<Object>()

var filteredIndexes = array.filter{$0.name = "Sane"} // How to implement this?
1
  • 2
    let indexes = array.enumerated().flatMap { (index, element) -> Int? in return element.name == "Sane" ? index: nil}? Adapted from stackoverflow.com/questions/38225121/… Commented Mar 8, 2018 at 11:15

3 Answers 3

2

There are several ways to achieve your goal. For instance, you can filter Array.indices instead of the array itself.

Self contained example:

struct Object {
    let name:String
    let goal:String
}

let objects = [Object(name: "John", goal: "a"),Object(name: "Jane", goal: "a"),Object(name: "John", goal: "c"),Object(name: "Pete", goal: "d")]
let nameToBeFound = "John"
let filteredIndices = objects.indices.filter({objects[$0].name == nameToBeFound}) //[0,2]
Sign up to request clarification or add additional context in comments.

Comments

2
let animals = ["cat", "dog", "cat", "dog", "cat"]
let indexes = animals.enumerated().filter({ return $1 == "cat" }).map { return $0.offset }
print(indexes)

prints out [0, 2, 4]

Comments

1

As Lame said above, the solution from Return an array of index values from array of Bool where true can be adapted to this case:

let filteredIndices = objects.enumerated().flatMap { $0.element.name == "Sane" ? $0.offset : nil }

One could also define a custom extension

extension Sequence {
    func indices(where predicate: (Element) -> Bool ) -> [Int] {
        return enumerated().flatMap { predicate($0.element) ? $0.offset : nil }
    }
}

which is then used as

let filteredIndices = objects.indices(where: { $0.name == "Sane" })

Remark: In Swift 4.1, this flatMap() method has been renamed to compactMap()

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.