• 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 / Copy a segment of an array into a new array

Copy a segment of an array into a new array

Copy a segment of an array into a new array

The first argument is the array index to start at, and the second is the index to end on. Both are optional. If you omit the start index, it will start at the beginning. If you omit the end index, it will go to the end.

The original array is not modified.

var sandwiches = ['turkey', 'tuna', 'chicken salad', 'italian', 'blt', 'grilled cheese'];

// ['chicken salad', 'italian', 'blt', 'grilled cheese']
var fewerSandwiches = sandwiches.slice(2);

// ['chicken salad', 'italian', 'blt']
var fewerSandwiches2 = sandwiches.slice(2, 4);

To create a brand new copy of an array in its entirety, you can use slice() with no arguments.

var sandwichesCopy = sandwiches.slice();

Source

https://vanillajstoolkit.com/reference/arrays/array-slice/

Miscellaneous

Related Snippets:

  • Copy text to the clipboard
  • Insert an element at the end of a set of elements inside a shared parent
  • How To Check If a Variable is a String in JavaScript
  • Insert an element at the beginning of a set elements inside a shared parent

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers