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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,752 questions

55,516 answers

573 users

How to remove every N‑th element from an array JavaScript

1 Answer

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

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

    It performs a single pass over the input array. JavaScript 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.length inside the loop.
*/
function removeEveryNth(items, n) {
    if (n <= 0) {
        throw new Error("n must be a positive integer");
    }

    const size = items.length;   // capture size once
    const result = [];           // output array

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

    return result;
}

/*
    Keeping the main execution block small and focused makes the program
    easy to extend. Here we demonstrate the function with a simple example.
*/
const data = Array.from({ length: 20 }, (_, i) => i + 1);  // numbers 1–20
const n = 3;                                               // remove every 3rd element

const cleaned = removeEveryNth(data, n);

console.log("Original:", data.join(" "));
console.log(`After removing every ${n}-th element:`, cleaned.join(" "));



/*
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 1 day ago by avibootz
...