0

I have a question and I hope that one of you can help me: I need to find the positions of an element in an array. For example:

var elements: [String] = ["a","b","c","a","c"]
var element = "a"

I need to know in what positions is the element, in this case 0,3 I have tried with some nested for loops but it was a mess, can you help me? Thanks

1 Answers1

0

Try this out:

var elements: [String] = ["a","b","c","a","c"]
var element = "a"
let indexes = elements.enumerated().compactMap { index, elem -> Int? in
  guard elem == element else { return nil }
  return index
}
print(indexes) // It will print [0, 3]
alanpaivaa
  • 1,959
  • 1
  • 14
  • 23