Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index(of:) to return multiple indices?

Here is a group array.

var group = ["H","H","E","D",
             "G","D","G","E",
             "D","B","A","B",
             "A","A","G","C",
             "C","H","D","G",
             "H","B","E","F",
             "F","C","E","A",
             "B","C","F","F"]

I want to do something like this to find indices of "A".

group.index(of: "A"!)

But this will return only first index, but not other indices for next three "A"s.

print(group.index(of: "A")!) //10

What do I do to get the program to return all four indices for "A"?

like image 525
jamryu Avatar asked Feb 05 '18 20:02

jamryu


People also ask

How do I return multiple indices in Python?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.


1 Answers

You might use a combination of enumerated and compactMap:

let indexArray = group.enumerated().compactMap {
   $0.element == "A" ? $0.offset : nil
}    
print(indexArray) // [10, 12, 13, 27]
like image 78
Andrea Mugnaini Avatar answered Sep 23 '22 19:09

Andrea Mugnaini