Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,401 questions

56,365 answers

573 users

How to remove every N‑th element from an array in Swift

1 Answer

0 votes
// ------------------------------------------------------------
// A small program demonstrating how to remove every Nth element
// from an Array using clear, expressive Swift patterns.
// ------------------------------------------------------------

import Foundation

/*
    removeEveryNth returns a new array with every Nth element removed.

    Swift arrays use zero‑based indexing, so we check (index + 1) % n != 0
    to keep elements that are *not* in the Nth position.

    The variable "size" captures the array length before the loop,
    which avoids repeatedly accessing items.count inside the loop.

    A new array is allocated with enough capacity to avoid repeated
    growth operations during append.
*/
func removeEveryNth<T>(_ items: [T], n: Int) -> [T] {
    precondition(n > 0, "n must be a positive integer")

    let size: Int = items.count          // capture size once
    var result: [T] = []                 // output array
    result.reserveCapacity(size)         // reserve capacity for efficiency

    for i in 0..<size {
        if (i + 1) % n != 0 {
            result.append(items[i])
        }
    }

    return result
}

/*
    main demonstrates the function with a simple example.
    Keeping main small and focused makes the program easy to extend.
*/
func main() {
    let data: [Int] = Array(1...20)   // Example array: numbers 1–20
    let n: Int = 3                    // Remove every 3rd element

    let cleaned: [Int] = removeEveryNth(data, n: n)

    // Build space‑separated strings without needing escaped quotes
    let originalString = data.map { String($0) }.joined(separator: " ")
    let cleanedString  = cleaned.map { String($0) }.joined(separator: " ")

    print("Original: \(originalString)")
    print("After removing every \(n)-th element: \(cleanedString)")
}

main()



/*
run:

Original: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After removing every 3-th element: 1 2 4 5 7 8 10 11 13 14 16 17 19 20

*/

 



answered Aug 16 by avibootz
...