Oleg Gordiichuk Oleg Gordiichuk - 2 months ago 5
Swift Question

Swift array remove consecutive numbers via filter

How it is possible to write

filter
function that will remove consecutive numbers from array.

Example:

let input = [1,2,3,4,8,10,12,19]
//Expected filter function.
let output = [8,10,12,19]

Answer

You can use flatMap which acts as a map and a filter against nil:

let output = input.enumerated().flatMap { index, element in
    return index > 0 && input[index - 1] + 1 == element ? nil : element
}

print(output) // [1, 8, 10, 12, 19]
Comments