Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an array of indexes, how can I filter an array in swift?

Tags:

ios

swift

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(...)
like image 541
aneuryzm Avatar asked Jul 04 '16 09:07

aneuryzm


People also ask

Can you filter an array?

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.

How do you find the index of an Element in an array in Swift?

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 .


1 Answers

Assuming that

  • the given indices are in increasing order, and
  • all indices are valid for the array (i.e. less than the number of elements),

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.

like image 132
Martin R Avatar answered Nov 17 '22 00:11

Martin R