Given an array of indexes I would like to get a subarray of myArray, with the items at those indexes. I'm currently iterating the indexes array to create a subarray, but I'm wondering if this can be achieved by using the .filter function.
var indexes = [3,4,9,11]
myArray.filter(...)
Using filter() on an Array of Numbers The item argument is a reference to the current element in the array as filter() checks it against the condition . This is useful for accessing properties, in the case of objects. If the current item passes the condition , it gets returned to the new array.
To find the index of a specific element in an Array in Swift, call firstIndex() method and pass the specific element for of parameter. Array. firstIndex(of: Element) returns the index of the first match of specified element in the array. If specified element is not present in the array, then this method returns nil .
Assuming that
then a simple map operation would work:
let indexes = [2, 4, 7]
let myArray = ["a", "b", "c", "d", "e", "f", "g", "h"]
let filtered = indexes.map { myArray[$0] }
print(filtered) //["c", "e", "h"]
Remark: In earlier Swift releases, there was a PermutationGenerator
exactly for this purpose:
let filtered = Array(PermutationGenerator(elements: myArray, indices: indexes))
print(filtered) //["c", "e", "h"]
However, this has been deprecated in Swift 2.2 and will be removed in Swift 3. I haven't seen a Swift 3 replacement yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With