• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Return every nth element in an array

Return every nth element in an array

Return every nth element in an array

Use Array.prototype.filter() to create a new array that contains every nth element of a given array.

const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);

// EXAMPLE
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]

Source

https://www.30secondsofcode.org/js/s/every-nth

Miscellaneous

Related Snippets:

  • Return all elements in an array except for the first one
  • Aliases with JavaScript Destructuring
  • Count elements in an array
  • Add special characters to text to print in color in the console

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2023 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us