Reputation:
I have an array containing arrays of integers like so:
[[1,2], [1,2,3], [1], [1]]
I want to go over this and transform any arrays with a count > 2 to have only two members. In this example above, the [1,2,3] would become [1,2] or [2,3] or [1,3] I'm not fussed which, just that one of the digits is removed.
I've tried doing a nested for in, however due to it making the array a constant, I can't mutate it inside this loop, and I've briefly looked at the map, filter and reduce on Array, however I can't seem to find a way to utilise them to get this to work. Any ideas would be great!
Upvotes: 0
Views: 287
Reputation: 230
You can use suffix(_ maxLength:)
or prefix(_ maxLength:)
.
Example below:
let array = [[1,2], [1,2,3], [1], [1]]
let result = array.map { Array($0.suffix(2)) }
print(result)
// it prints: [[1, 2], [2, 3], [1], [1]]
Upvotes: 2