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

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Forum
  • 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:

  • Short-Circuit Evaluation Using &&
  • Make a draggable element
  • Create a one time event handler
  • Add characters to the end of a string if it’s less than a certain length

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2022 JavaScriptSource.com

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