Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reduce(into:_:) to filter adjacent equal elements

Tags:

arrays

swift

fold

The Swift Standard Library API specifies that Array has a method reduce(into:_:) that returns the result of combining the elements of the sequence using the given closure.

The API docs mention that "you can use this method on an array of integers to filter adjacent equal entries". Can someone provide an example of how this would be done?

like image 661
lreichold Avatar asked Jul 20 '26 18:07

lreichold


1 Answers

You could eliminate runs of equal numbers like this:

let numbers = [1, 1, 2, 2, 2, 3, 4, 4, 5, 4, 3]
let filtered = numbers.reduce(into: [Int]()) { newArray, number in
    if newArray.last != number { newArray.append(number) }
}

print(filtered)

[1, 2, 3, 4, 5, 4, 3]

like image 136
vacawama Avatar answered Jul 23 '26 06:07

vacawama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!