Swift - How to get indexes of filtered items of arrayfind repeatable string position in arrayIndex of an element in arrayAfter Swift 3 conversion, I can't get rid of error: “Ambiguous use of 'indexOfObject(passingTest:)'”Get key and indices of selected elements SwiftHow do I check if an array includes an object in JavaScript?How to append something to an array?How to insert an item into an array at a specific index (JavaScript)?How do I determine whether an array contains a particular value in Java?How do I empty an array in JavaScript?How to check if an object is an array?How do I remove a particular element from an array in JavaScript?How can I add new array elements at the beginning of an array in Javascript?Swift for loop: for index, element in array?Swift Beta performance: sorting arrays

Is there such a thing as too inconvenient?

What is the evidence on the danger of feeding whole blueberries and grapes to infants and toddlers?

How to compare two different formulations of a problem?

How to avoid using System.String with Rfc2898DeriveBytes in C#

Why were movies shot on film shot at 24 frames per second?

Can I submit a paper under an alias so as to avoid trouble in my country?

Why doesn't mathematics collapse down, even though humans quite often make mistakes in their proofs?

Is it appropriate for a business to ask me for my credit report?

How can I pack my food so it doesn't smell?

How does the government purchase things?

How to "know" if I have a passion?

Sous vide chicken without an internal temperature of 165 °F (75 °C)

Changing a TGV booking

How much code would a codegolf golf if a codegolf could golf code?

Why didn’t Doctor Strange stay in the original winning timeline?

Is a butterfly one or two animals?

!I!n!s!e!r!t! !n!b!e!t!w!e!e!n!

How to organize ideas to start writing a novel?

A second course in the representation theory

How to create a summation symbol with a vertical bar?

Designing a prison for a telekinetic race

Don't teach Dhamma to those who can't appreciate it or aren't interested

Ruling for Grappling a Creature Underwater While you are on Land?

jersey vs sweater



Swift - How to get indexes of filtered items of array


find repeatable string position in arrayIndex of an element in arrayAfter Swift 3 conversion, I can't get rid of error: “Ambiguous use of 'indexOfObject(passingTest:)'”Get key and indices of selected elements SwiftHow do I check if an array includes an object in JavaScript?How to append something to an array?How to insert an item into an array at a specific index (JavaScript)?How do I determine whether an array contains a particular value in Java?How do I empty an array in JavaScript?How to check if an object is an array?How do I remove a particular element from an array in JavaScript?How can I add new array elements at the beginning of an array in Javascript?Swift for loop: for index, element in array?Swift Beta performance: sorting arrays






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








18















let items: [String] = ["A", "B", "A", "C", "A", "D"]

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]


Does Swift 3 support a function like whatFunction(_: Element)?



If not, what is the most efficient logic?










share|improve this question


























  • you can find this way let indexOfA = arr.index(of: "a")

    – Bhupat Bheda
    Aug 29 '17 at 7:29











  • @BhupatBheda Thank you, but index(of: Element) just returns Int?. The function that I need should returns [Int]?.

    – Byoth
    Aug 29 '17 at 7:37











  • Possible duplicate of After Swift 3 conversion, I can't get rid of error: "Ambiguous use of 'indexOfObject(passingTest:)'"

    – Larme
    Aug 29 '17 at 9:25

















18















let items: [String] = ["A", "B", "A", "C", "A", "D"]

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]


Does Swift 3 support a function like whatFunction(_: Element)?



If not, what is the most efficient logic?










share|improve this question


























  • you can find this way let indexOfA = arr.index(of: "a")

    – Bhupat Bheda
    Aug 29 '17 at 7:29











  • @BhupatBheda Thank you, but index(of: Element) just returns Int?. The function that I need should returns [Int]?.

    – Byoth
    Aug 29 '17 at 7:37











  • Possible duplicate of After Swift 3 conversion, I can't get rid of error: "Ambiguous use of 'indexOfObject(passingTest:)'"

    – Larme
    Aug 29 '17 at 9:25













18












18








18


3






let items: [String] = ["A", "B", "A", "C", "A", "D"]

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]


Does Swift 3 support a function like whatFunction(_: Element)?



If not, what is the most efficient logic?










share|improve this question
















let items: [String] = ["A", "B", "A", "C", "A", "D"]

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]


Does Swift 3 support a function like whatFunction(_: Element)?



If not, what is the most efficient logic?







arrays swift swift3 swift4






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 29 '17 at 11:53









Julien Kode

1,9726 silver badges20 bronze badges




1,9726 silver badges20 bronze badges










asked Aug 29 '17 at 7:27









ByothByoth

3892 gold badges6 silver badges18 bronze badges




3892 gold badges6 silver badges18 bronze badges















  • you can find this way let indexOfA = arr.index(of: "a")

    – Bhupat Bheda
    Aug 29 '17 at 7:29











  • @BhupatBheda Thank you, but index(of: Element) just returns Int?. The function that I need should returns [Int]?.

    – Byoth
    Aug 29 '17 at 7:37











  • Possible duplicate of After Swift 3 conversion, I can't get rid of error: "Ambiguous use of 'indexOfObject(passingTest:)'"

    – Larme
    Aug 29 '17 at 9:25

















  • you can find this way let indexOfA = arr.index(of: "a")

    – Bhupat Bheda
    Aug 29 '17 at 7:29











  • @BhupatBheda Thank you, but index(of: Element) just returns Int?. The function that I need should returns [Int]?.

    – Byoth
    Aug 29 '17 at 7:37











  • Possible duplicate of After Swift 3 conversion, I can't get rid of error: "Ambiguous use of 'indexOfObject(passingTest:)'"

    – Larme
    Aug 29 '17 at 9:25
















you can find this way let indexOfA = arr.index(of: "a")

– Bhupat Bheda
Aug 29 '17 at 7:29





you can find this way let indexOfA = arr.index(of: "a")

– Bhupat Bheda
Aug 29 '17 at 7:29













@BhupatBheda Thank you, but index(of: Element) just returns Int?. The function that I need should returns [Int]?.

– Byoth
Aug 29 '17 at 7:37





@BhupatBheda Thank you, but index(of: Element) just returns Int?. The function that I need should returns [Int]?.

– Byoth
Aug 29 '17 at 7:37













Possible duplicate of After Swift 3 conversion, I can't get rid of error: "Ambiguous use of 'indexOfObject(passingTest:)'"

– Larme
Aug 29 '17 at 9:25





Possible duplicate of After Swift 3 conversion, I can't get rid of error: "Ambiguous use of 'indexOfObject(passingTest:)'"

– Larme
Aug 29 '17 at 9:25












7 Answers
7






active

oldest

votes


















14














You can create your own extension for arrays.



extension Array where Element: Equatable 
func indexes(of element: Element) -> [Int]
return self.enumerated().filter( element == $0.element ).map( $0.offset )




You can simply call it like this



items.indexes(of: "A") // [0, 2, 4]
items.indexes(of: "B") // [1]





share|improve this answer

























  • Awesome! Thanks!

    – Byoth
    Aug 29 '17 at 7:45











  • This is an EF'n Fantastic Answer!

    – jlstr
    Jul 12 '18 at 21:11


















21














You can filter the indices of the array directly, it avoids the extra mapping.



let items = ["A", "B", "A", "C", "A", "D"]
let filteredIndices = items.indices.filter items[$0] == "A"


or as Array extension:



extension Array where Element: Equatable 

func whatFunction(_ value : Element) -> [Int]
return self.indices.filter self[$0] == value




items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]


or still more generic



extension Collection where Element: Equatable 

func whatFunction(_ value : Element) -> [Index]
return self.indices.filter self[$0] == value








share|improve this answer



























  • You might as well extend Collection since the implementation uses nothing that is specific to arrays.

    – Tim Vermeulen
    Jul 14 '18 at 19:17











  • @vadian would you like to check stackoverflow.com/q/54088250/4601170 and help me please?

    – EI Captain v2.0
    Jan 8 at 8:55



















10














You can achieve this by chain of:




  1. enumerated() - add indexes;


  2. filter() out unnecessary items;


  3. map() our indexes.

Example (works in Swift 3 - Swift 4.x):



let items: [String] = ["A", "B", "A", "C", "A", "D"] 
print(items.enumerated().filter( $0.element == "A" ).map( $0.offset )) // -> [0, 2, 4]



Another way is using flatMap, which allows you to check the element and return index if needed in one closure.



Example (works in Swift 3 - Swift 4.0):



print(items.enumerated().flatMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]


But since Swift 4.1 flatMap that can return non-nil objects become deprecated and instead you should use compactMap.



Example (works since Swift 4.1):



print(items.enumerated().compactMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]



And the cleanest and the most memory-cheap way is to iterate through array indices and check if element of array at current index equals to required element.



Example (works in Swift 3 - Swift 4.x):



print(items.indices.filter( items[$0] == "A" )) // -> [0, 2, 4]





share|improve this answer






















  • 1





    Note that you could also combine filter and map into flatMap, as Julien did, but more details in the answer is good too ;)

    – David Berry
    Aug 29 '17 at 8:22











  • @DavidBerry, sure, but i think this is more advanced topic for author)

    – pacification
    Aug 29 '17 at 8:24












  • @DavidBerry What would be the point of that?

    – Tim Vermeulen
    Aug 30 '17 at 13:33











  • Just another approach is all. Personally I usually prefer to split filter and map into separate steps if they have different basis, as this does. If on the other hand one wanted to filter and map on the same property, flatMap makes more sense.

    – David Berry
    Aug 31 '17 at 6:10


















8














In Swift 3 and Swift 4 you can do that:



let items: [String] = ["A", "B", "A", "C", "A", "D"]

extension Array where Element: Equatable

func indexes(of item: Element) -> [Int]
return enumerated().compactMap $0.element == item ? $0.offset : nil



items.indexes(of: "A")


I hope my answer was helpful 😊






share|improve this answer


































    2














    you can use it like that :



     let items: [String] = ["A", "B", "A", "C", "A", "D"]

    let indexes = items.enumerated().filter
    $0.element == "A"
    .map$0.offset

    print(indexes)





    share|improve this answer
































      1














      just copy and paste



      extension Array 
      func whatFunction(_ ids : String) -> [Int]

      var mutableArr = [Int]()
      for i in 0..<self.count
      if ((self[i] as! String) == ids)
      mutableArr.append(i)


      return mutableArr








      share|improve this answer


































        0














        For example finding the indices of p_last values that are in inds1 array: (swift 4+)



        let p_last = [51,42]
        let inds1 = [1,3,51,42,4]
        let idx1 = Array(inds1.filter p_last.contains($0) .indices)


        idx1 = [0,1]






        share|improve this answer



























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45933149%2fswift-how-to-get-indexes-of-filtered-items-of-array%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          14














          You can create your own extension for arrays.



          extension Array where Element: Equatable 
          func indexes(of element: Element) -> [Int]
          return self.enumerated().filter( element == $0.element ).map( $0.offset )




          You can simply call it like this



          items.indexes(of: "A") // [0, 2, 4]
          items.indexes(of: "B") // [1]





          share|improve this answer

























          • Awesome! Thanks!

            – Byoth
            Aug 29 '17 at 7:45











          • This is an EF'n Fantastic Answer!

            – jlstr
            Jul 12 '18 at 21:11















          14














          You can create your own extension for arrays.



          extension Array where Element: Equatable 
          func indexes(of element: Element) -> [Int]
          return self.enumerated().filter( element == $0.element ).map( $0.offset )




          You can simply call it like this



          items.indexes(of: "A") // [0, 2, 4]
          items.indexes(of: "B") // [1]





          share|improve this answer

























          • Awesome! Thanks!

            – Byoth
            Aug 29 '17 at 7:45











          • This is an EF'n Fantastic Answer!

            – jlstr
            Jul 12 '18 at 21:11













          14












          14








          14







          You can create your own extension for arrays.



          extension Array where Element: Equatable 
          func indexes(of element: Element) -> [Int]
          return self.enumerated().filter( element == $0.element ).map( $0.offset )




          You can simply call it like this



          items.indexes(of: "A") // [0, 2, 4]
          items.indexes(of: "B") // [1]





          share|improve this answer













          You can create your own extension for arrays.



          extension Array where Element: Equatable 
          func indexes(of element: Element) -> [Int]
          return self.enumerated().filter( element == $0.element ).map( $0.offset )




          You can simply call it like this



          items.indexes(of: "A") // [0, 2, 4]
          items.indexes(of: "B") // [1]






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 29 '17 at 7:33









          YannickYannick

          2,3071 gold badge10 silver badges25 bronze badges




          2,3071 gold badge10 silver badges25 bronze badges















          • Awesome! Thanks!

            – Byoth
            Aug 29 '17 at 7:45











          • This is an EF'n Fantastic Answer!

            – jlstr
            Jul 12 '18 at 21:11

















          • Awesome! Thanks!

            – Byoth
            Aug 29 '17 at 7:45











          • This is an EF'n Fantastic Answer!

            – jlstr
            Jul 12 '18 at 21:11
















          Awesome! Thanks!

          – Byoth
          Aug 29 '17 at 7:45





          Awesome! Thanks!

          – Byoth
          Aug 29 '17 at 7:45













          This is an EF'n Fantastic Answer!

          – jlstr
          Jul 12 '18 at 21:11





          This is an EF'n Fantastic Answer!

          – jlstr
          Jul 12 '18 at 21:11













          21














          You can filter the indices of the array directly, it avoids the extra mapping.



          let items = ["A", "B", "A", "C", "A", "D"]
          let filteredIndices = items.indices.filter items[$0] == "A"


          or as Array extension:



          extension Array where Element: Equatable 

          func whatFunction(_ value : Element) -> [Int]
          return self.indices.filter self[$0] == value




          items.whatFunction("A") // -> [0, 2, 4]
          items.whatFunction("B") // -> [1]


          or still more generic



          extension Collection where Element: Equatable 

          func whatFunction(_ value : Element) -> [Index]
          return self.indices.filter self[$0] == value








          share|improve this answer



























          • You might as well extend Collection since the implementation uses nothing that is specific to arrays.

            – Tim Vermeulen
            Jul 14 '18 at 19:17











          • @vadian would you like to check stackoverflow.com/q/54088250/4601170 and help me please?

            – EI Captain v2.0
            Jan 8 at 8:55
















          21














          You can filter the indices of the array directly, it avoids the extra mapping.



          let items = ["A", "B", "A", "C", "A", "D"]
          let filteredIndices = items.indices.filter items[$0] == "A"


          or as Array extension:



          extension Array where Element: Equatable 

          func whatFunction(_ value : Element) -> [Int]
          return self.indices.filter self[$0] == value




          items.whatFunction("A") // -> [0, 2, 4]
          items.whatFunction("B") // -> [1]


          or still more generic



          extension Collection where Element: Equatable 

          func whatFunction(_ value : Element) -> [Index]
          return self.indices.filter self[$0] == value








          share|improve this answer



























          • You might as well extend Collection since the implementation uses nothing that is specific to arrays.

            – Tim Vermeulen
            Jul 14 '18 at 19:17











          • @vadian would you like to check stackoverflow.com/q/54088250/4601170 and help me please?

            – EI Captain v2.0
            Jan 8 at 8:55














          21












          21








          21







          You can filter the indices of the array directly, it avoids the extra mapping.



          let items = ["A", "B", "A", "C", "A", "D"]
          let filteredIndices = items.indices.filter items[$0] == "A"


          or as Array extension:



          extension Array where Element: Equatable 

          func whatFunction(_ value : Element) -> [Int]
          return self.indices.filter self[$0] == value




          items.whatFunction("A") // -> [0, 2, 4]
          items.whatFunction("B") // -> [1]


          or still more generic



          extension Collection where Element: Equatable 

          func whatFunction(_ value : Element) -> [Index]
          return self.indices.filter self[$0] == value








          share|improve this answer















          You can filter the indices of the array directly, it avoids the extra mapping.



          let items = ["A", "B", "A", "C", "A", "D"]
          let filteredIndices = items.indices.filter items[$0] == "A"


          or as Array extension:



          extension Array where Element: Equatable 

          func whatFunction(_ value : Element) -> [Int]
          return self.indices.filter self[$0] == value




          items.whatFunction("A") // -> [0, 2, 4]
          items.whatFunction("B") // -> [1]


          or still more generic



          extension Collection where Element: Equatable 

          func whatFunction(_ value : Element) -> [Index]
          return self.indices.filter self[$0] == value









          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Oct 22 '18 at 15:09

























          answered Aug 29 '17 at 8:21









          vadianvadian

          170k20 gold badges186 silver badges208 bronze badges




          170k20 gold badges186 silver badges208 bronze badges















          • You might as well extend Collection since the implementation uses nothing that is specific to arrays.

            – Tim Vermeulen
            Jul 14 '18 at 19:17











          • @vadian would you like to check stackoverflow.com/q/54088250/4601170 and help me please?

            – EI Captain v2.0
            Jan 8 at 8:55


















          • You might as well extend Collection since the implementation uses nothing that is specific to arrays.

            – Tim Vermeulen
            Jul 14 '18 at 19:17











          • @vadian would you like to check stackoverflow.com/q/54088250/4601170 and help me please?

            – EI Captain v2.0
            Jan 8 at 8:55

















          You might as well extend Collection since the implementation uses nothing that is specific to arrays.

          – Tim Vermeulen
          Jul 14 '18 at 19:17





          You might as well extend Collection since the implementation uses nothing that is specific to arrays.

          – Tim Vermeulen
          Jul 14 '18 at 19:17













          @vadian would you like to check stackoverflow.com/q/54088250/4601170 and help me please?

          – EI Captain v2.0
          Jan 8 at 8:55






          @vadian would you like to check stackoverflow.com/q/54088250/4601170 and help me please?

          – EI Captain v2.0
          Jan 8 at 8:55












          10














          You can achieve this by chain of:




          1. enumerated() - add indexes;


          2. filter() out unnecessary items;


          3. map() our indexes.

          Example (works in Swift 3 - Swift 4.x):



          let items: [String] = ["A", "B", "A", "C", "A", "D"] 
          print(items.enumerated().filter( $0.element == "A" ).map( $0.offset )) // -> [0, 2, 4]



          Another way is using flatMap, which allows you to check the element and return index if needed in one closure.



          Example (works in Swift 3 - Swift 4.0):



          print(items.enumerated().flatMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]


          But since Swift 4.1 flatMap that can return non-nil objects become deprecated and instead you should use compactMap.



          Example (works since Swift 4.1):



          print(items.enumerated().compactMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]



          And the cleanest and the most memory-cheap way is to iterate through array indices and check if element of array at current index equals to required element.



          Example (works in Swift 3 - Swift 4.x):



          print(items.indices.filter( items[$0] == "A" )) // -> [0, 2, 4]





          share|improve this answer






















          • 1





            Note that you could also combine filter and map into flatMap, as Julien did, but more details in the answer is good too ;)

            – David Berry
            Aug 29 '17 at 8:22











          • @DavidBerry, sure, but i think this is more advanced topic for author)

            – pacification
            Aug 29 '17 at 8:24












          • @DavidBerry What would be the point of that?

            – Tim Vermeulen
            Aug 30 '17 at 13:33











          • Just another approach is all. Personally I usually prefer to split filter and map into separate steps if they have different basis, as this does. If on the other hand one wanted to filter and map on the same property, flatMap makes more sense.

            – David Berry
            Aug 31 '17 at 6:10















          10














          You can achieve this by chain of:




          1. enumerated() - add indexes;


          2. filter() out unnecessary items;


          3. map() our indexes.

          Example (works in Swift 3 - Swift 4.x):



          let items: [String] = ["A", "B", "A", "C", "A", "D"] 
          print(items.enumerated().filter( $0.element == "A" ).map( $0.offset )) // -> [0, 2, 4]



          Another way is using flatMap, which allows you to check the element and return index if needed in one closure.



          Example (works in Swift 3 - Swift 4.0):



          print(items.enumerated().flatMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]


          But since Swift 4.1 flatMap that can return non-nil objects become deprecated and instead you should use compactMap.



          Example (works since Swift 4.1):



          print(items.enumerated().compactMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]



          And the cleanest and the most memory-cheap way is to iterate through array indices and check if element of array at current index equals to required element.



          Example (works in Swift 3 - Swift 4.x):



          print(items.indices.filter( items[$0] == "A" )) // -> [0, 2, 4]





          share|improve this answer






















          • 1





            Note that you could also combine filter and map into flatMap, as Julien did, but more details in the answer is good too ;)

            – David Berry
            Aug 29 '17 at 8:22











          • @DavidBerry, sure, but i think this is more advanced topic for author)

            – pacification
            Aug 29 '17 at 8:24












          • @DavidBerry What would be the point of that?

            – Tim Vermeulen
            Aug 30 '17 at 13:33











          • Just another approach is all. Personally I usually prefer to split filter and map into separate steps if they have different basis, as this does. If on the other hand one wanted to filter and map on the same property, flatMap makes more sense.

            – David Berry
            Aug 31 '17 at 6:10













          10












          10








          10







          You can achieve this by chain of:




          1. enumerated() - add indexes;


          2. filter() out unnecessary items;


          3. map() our indexes.

          Example (works in Swift 3 - Swift 4.x):



          let items: [String] = ["A", "B", "A", "C", "A", "D"] 
          print(items.enumerated().filter( $0.element == "A" ).map( $0.offset )) // -> [0, 2, 4]



          Another way is using flatMap, which allows you to check the element and return index if needed in one closure.



          Example (works in Swift 3 - Swift 4.0):



          print(items.enumerated().flatMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]


          But since Swift 4.1 flatMap that can return non-nil objects become deprecated and instead you should use compactMap.



          Example (works since Swift 4.1):



          print(items.enumerated().compactMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]



          And the cleanest and the most memory-cheap way is to iterate through array indices and check if element of array at current index equals to required element.



          Example (works in Swift 3 - Swift 4.x):



          print(items.indices.filter( items[$0] == "A" )) // -> [0, 2, 4]





          share|improve this answer















          You can achieve this by chain of:




          1. enumerated() - add indexes;


          2. filter() out unnecessary items;


          3. map() our indexes.

          Example (works in Swift 3 - Swift 4.x):



          let items: [String] = ["A", "B", "A", "C", "A", "D"] 
          print(items.enumerated().filter( $0.element == "A" ).map( $0.offset )) // -> [0, 2, 4]



          Another way is using flatMap, which allows you to check the element and return index if needed in one closure.



          Example (works in Swift 3 - Swift 4.0):



          print(items.enumerated().flatMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]


          But since Swift 4.1 flatMap that can return non-nil objects become deprecated and instead you should use compactMap.



          Example (works since Swift 4.1):



          print(items.enumerated().compactMap $0.element == "A" ? $0.offset : nil ) // -> [0, 2, 4]



          And the cleanest and the most memory-cheap way is to iterate through array indices and check if element of array at current index equals to required element.



          Example (works in Swift 3 - Swift 4.x):



          print(items.indices.filter( items[$0] == "A" )) // -> [0, 2, 4]






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jul 14 '18 at 11:34

























          answered Aug 29 '17 at 7:34









          pacificationpacification

          3,8473 gold badges17 silver badges39 bronze badges




          3,8473 gold badges17 silver badges39 bronze badges










          • 1





            Note that you could also combine filter and map into flatMap, as Julien did, but more details in the answer is good too ;)

            – David Berry
            Aug 29 '17 at 8:22











          • @DavidBerry, sure, but i think this is more advanced topic for author)

            – pacification
            Aug 29 '17 at 8:24












          • @DavidBerry What would be the point of that?

            – Tim Vermeulen
            Aug 30 '17 at 13:33











          • Just another approach is all. Personally I usually prefer to split filter and map into separate steps if they have different basis, as this does. If on the other hand one wanted to filter and map on the same property, flatMap makes more sense.

            – David Berry
            Aug 31 '17 at 6:10












          • 1





            Note that you could also combine filter and map into flatMap, as Julien did, but more details in the answer is good too ;)

            – David Berry
            Aug 29 '17 at 8:22











          • @DavidBerry, sure, but i think this is more advanced topic for author)

            – pacification
            Aug 29 '17 at 8:24












          • @DavidBerry What would be the point of that?

            – Tim Vermeulen
            Aug 30 '17 at 13:33











          • Just another approach is all. Personally I usually prefer to split filter and map into separate steps if they have different basis, as this does. If on the other hand one wanted to filter and map on the same property, flatMap makes more sense.

            – David Berry
            Aug 31 '17 at 6:10







          1




          1





          Note that you could also combine filter and map into flatMap, as Julien did, but more details in the answer is good too ;)

          – David Berry
          Aug 29 '17 at 8:22





          Note that you could also combine filter and map into flatMap, as Julien did, but more details in the answer is good too ;)

          – David Berry
          Aug 29 '17 at 8:22













          @DavidBerry, sure, but i think this is more advanced topic for author)

          – pacification
          Aug 29 '17 at 8:24






          @DavidBerry, sure, but i think this is more advanced topic for author)

          – pacification
          Aug 29 '17 at 8:24














          @DavidBerry What would be the point of that?

          – Tim Vermeulen
          Aug 30 '17 at 13:33





          @DavidBerry What would be the point of that?

          – Tim Vermeulen
          Aug 30 '17 at 13:33













          Just another approach is all. Personally I usually prefer to split filter and map into separate steps if they have different basis, as this does. If on the other hand one wanted to filter and map on the same property, flatMap makes more sense.

          – David Berry
          Aug 31 '17 at 6:10





          Just another approach is all. Personally I usually prefer to split filter and map into separate steps if they have different basis, as this does. If on the other hand one wanted to filter and map on the same property, flatMap makes more sense.

          – David Berry
          Aug 31 '17 at 6:10











          8














          In Swift 3 and Swift 4 you can do that:



          let items: [String] = ["A", "B", "A", "C", "A", "D"]

          extension Array where Element: Equatable

          func indexes(of item: Element) -> [Int]
          return enumerated().compactMap $0.element == item ? $0.offset : nil



          items.indexes(of: "A")


          I hope my answer was helpful 😊






          share|improve this answer































            8














            In Swift 3 and Swift 4 you can do that:



            let items: [String] = ["A", "B", "A", "C", "A", "D"]

            extension Array where Element: Equatable

            func indexes(of item: Element) -> [Int]
            return enumerated().compactMap $0.element == item ? $0.offset : nil



            items.indexes(of: "A")


            I hope my answer was helpful 😊






            share|improve this answer





























              8












              8








              8







              In Swift 3 and Swift 4 you can do that:



              let items: [String] = ["A", "B", "A", "C", "A", "D"]

              extension Array where Element: Equatable

              func indexes(of item: Element) -> [Int]
              return enumerated().compactMap $0.element == item ? $0.offset : nil



              items.indexes(of: "A")


              I hope my answer was helpful 😊






              share|improve this answer















              In Swift 3 and Swift 4 you can do that:



              let items: [String] = ["A", "B", "A", "C", "A", "D"]

              extension Array where Element: Equatable

              func indexes(of item: Element) -> [Int]
              return enumerated().compactMap $0.element == item ? $0.offset : nil



              items.indexes(of: "A")


              I hope my answer was helpful 😊







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 27 at 15:29









              kaurrauk

              421 silver badge7 bronze badges




              421 silver badge7 bronze badges










              answered Aug 29 '17 at 7:34









              Julien KodeJulien Kode

              1,9726 silver badges20 bronze badges




              1,9726 silver badges20 bronze badges
























                  2














                  you can use it like that :



                   let items: [String] = ["A", "B", "A", "C", "A", "D"]

                  let indexes = items.enumerated().filter
                  $0.element == "A"
                  .map$0.offset

                  print(indexes)





                  share|improve this answer





























                    2














                    you can use it like that :



                     let items: [String] = ["A", "B", "A", "C", "A", "D"]

                    let indexes = items.enumerated().filter
                    $0.element == "A"
                    .map$0.offset

                    print(indexes)





                    share|improve this answer



























                      2












                      2








                      2







                      you can use it like that :



                       let items: [String] = ["A", "B", "A", "C", "A", "D"]

                      let indexes = items.enumerated().filter
                      $0.element == "A"
                      .map$0.offset

                      print(indexes)





                      share|improve this answer













                      you can use it like that :



                       let items: [String] = ["A", "B", "A", "C", "A", "D"]

                      let indexes = items.enumerated().filter
                      $0.element == "A"
                      .map$0.offset

                      print(indexes)






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 29 '17 at 7:41









                      Abdelahad DarwishAbdelahad Darwish

                      4,6051 gold badge9 silver badges28 bronze badges




                      4,6051 gold badge9 silver badges28 bronze badges
























                          1














                          just copy and paste



                          extension Array 
                          func whatFunction(_ ids : String) -> [Int]

                          var mutableArr = [Int]()
                          for i in 0..<self.count
                          if ((self[i] as! String) == ids)
                          mutableArr.append(i)


                          return mutableArr








                          share|improve this answer































                            1














                            just copy and paste



                            extension Array 
                            func whatFunction(_ ids : String) -> [Int]

                            var mutableArr = [Int]()
                            for i in 0..<self.count
                            if ((self[i] as! String) == ids)
                            mutableArr.append(i)


                            return mutableArr








                            share|improve this answer





























                              1












                              1








                              1







                              just copy and paste



                              extension Array 
                              func whatFunction(_ ids : String) -> [Int]

                              var mutableArr = [Int]()
                              for i in 0..<self.count
                              if ((self[i] as! String) == ids)
                              mutableArr.append(i)


                              return mutableArr








                              share|improve this answer















                              just copy and paste



                              extension Array 
                              func whatFunction(_ ids : String) -> [Int]

                              var mutableArr = [Int]()
                              for i in 0..<self.count
                              if ((self[i] as! String) == ids)
                              mutableArr.append(i)


                              return mutableArr









                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Aug 29 '17 at 7:56









                              3stud1ant3

                              3,3662 gold badges7 silver badges14 bronze badges




                              3,3662 gold badges7 silver badges14 bronze badges










                              answered Aug 29 '17 at 7:47









                              sejal thesiyasejal thesiya

                              397 bronze badges




                              397 bronze badges
























                                  0














                                  For example finding the indices of p_last values that are in inds1 array: (swift 4+)



                                  let p_last = [51,42]
                                  let inds1 = [1,3,51,42,4]
                                  let idx1 = Array(inds1.filter p_last.contains($0) .indices)


                                  idx1 = [0,1]






                                  share|improve this answer





























                                    0














                                    For example finding the indices of p_last values that are in inds1 array: (swift 4+)



                                    let p_last = [51,42]
                                    let inds1 = [1,3,51,42,4]
                                    let idx1 = Array(inds1.filter p_last.contains($0) .indices)


                                    idx1 = [0,1]






                                    share|improve this answer



























                                      0












                                      0








                                      0







                                      For example finding the indices of p_last values that are in inds1 array: (swift 4+)



                                      let p_last = [51,42]
                                      let inds1 = [1,3,51,42,4]
                                      let idx1 = Array(inds1.filter p_last.contains($0) .indices)


                                      idx1 = [0,1]






                                      share|improve this answer













                                      For example finding the indices of p_last values that are in inds1 array: (swift 4+)



                                      let p_last = [51,42]
                                      let inds1 = [1,3,51,42,4]
                                      let idx1 = Array(inds1.filter p_last.contains($0) .indices)


                                      idx1 = [0,1]







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Oct 22 '18 at 14:53









                                      bretcj7bretcj7

                                      1371 gold badge3 silver badges14 bronze badges




                                      1371 gold badge3 silver badges14 bronze badges






























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45933149%2fswift-how-to-get-indexes-of-filtered-items-of-array%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해