0

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!

1
  • What if an array have 5 elements would it drop 3 or just 1 element? Commented Sep 4, 2018 at 11:38

1 Answer 1

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.