Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove every nth element from swift array

Tags:

arrays

swift

Is there an easy way to remove every nth element from a swift array. For example, in the array below:

thisArray = [2.0, 4.0, 3.0, 1.0, 4.5, 3.3, 1.2, 3.6, 10.3, 4.4, 2.0, 13.0]

If n = 3 and start count from first element would like to return:

returnThis = [2.0, 4.0, 1.0, 4.5, 1.2, 3.6, 4.4, 2.0]
like image 986
user5672373 Avatar asked Aug 28 '16 21:08

user5672373


People also ask

How do you remove every nth element from an array?

Use Array#splice method to remove an element from the array. Where the first argument is defined as the index and second as the number elements to be deleted. To remove elements at 3rd position use a while loop which iterates in backward and then delete the element based on the position.

How do you clear an array in Swift?

To do that we will use the array's built-in function called removeAll(). Calling the removeAll() function will remove all elements from an array.

What is reduce in Swift?

reduce(_:_:) Returns the result of combining the elements of the sequence using the given closure.


2 Answers

// swift 4.1:
thisArray.enumerated().compactMap { index, element in index % 3 == 2 ? nil : element }
  • Use .enumerated() to attach the indices
  • Then use .compactMap to filter out items at indices 2, 5, 8, ... by returning nil, and strip the index for the rest by returning just element.

(If you are using Swift 4.0 or below, use .flatMap instead of .compactMap. The .compactMap method was introduced in Swift 4.1 by SE-0187)

(If you are stuck with Swift 2, use .enumerate() instead of .enumerated().)

like image 77
kennytm Avatar answered Oct 18 '22 12:10

kennytm


Since the Functional style solutions have already been posted I am using here an old fashion way approach

let nums = [2.0, 4.0, 3.0, 1.0, 4.5, 3.3, 1.2, 3.6, 10.3, 4.4, 2.0, 13.0]

var filteredNums = [Double]()
for elm in nums.enumerate() where elm.index % 3 != 2 {
    filteredNums.append(elm.element)
}
like image 22
Luca Angeletti Avatar answered Oct 18 '22 11:10

Luca Angeletti