JavaScript Array slice() Method
In this post, you will learn about the Array slicing using the slice() method of JavaScript programming language.
An array is a collection of key/value pairs. We can store more than one item in a single variable. i.e. array. An array in JavaScript can hold different elements that can store numbers, strings, and booleans in a single array.
JavaScript Array Slicing
The JavaScript arr.slice() method returns selected elements in an array, as a new array. It selects from a given start, up to a given end.
Syntax-array.slice(start, end)
Here, the start is the starting index from where the portion is to be extracted, and the end is the index up to which the portion is to be extracted. This method returns a new array containing the selected elements.
JavaScript display all array elements
const planets = ['Mercury','Venus','Earth','Mars','Jupiter','Saturn','Uranus','Neptune'];
const selected_planets = planets.slice(0);
console.log(selected_planets);
Output of the above code:
[ 'Mercury',
'Venus',
'Earth',
'Mars',
'Jupiter',
'Saturn',
'Uranus',
'Neptune' ]
JavaScript array slicing in given position range
const planets = ['Mercury','Venus','Earth','Mars','Jupiter','Saturn','Uranus','Neptune'];
const selected_planets = planets.slice(2, 5);
console.log(selected_planets);
Output of the above code:
[ 'Earth', 'Mars', 'Jupiter' ]
JavaScript array slicing with positive & negative
const planets = ['Mercury','Venus','Earth','Mars','Jupiter','Saturn','Uranus','Neptune'];
const selected_planets = planets.slice(2, -3);
console.log(selected_planets);
Output of the above code:
[ 'Earth', 'Mars', 'Jupiter' ]
JavaScript array slicing in given negative range
const planets = ['Mercury','Venus','Earth','Mars','Jupiter','Saturn','Uranus','Neptune'];
const selected_planets = planets.slice(-4, -2);
console.log(selected_planets);
Output of the above code:
[ 'Jupiter', 'Saturn' ]
Related Articles
Generate random numbers in JavaScriptJavaScript window location
Remove duplicates from array JavaScript
Scientific calculator JavaScript
How to reverse string in JavaScript
JavaScript display PDF in the browser using Ajax call
Parsing JSON in JavaScript
JavaScript speech recognition example
Select/deselect all checkboxes using JavaScript
Print specific part of a web page in javaScript
Dynamically Add/Delete HTML Table Rows Using JavaScript
jQuery Ajax serialize form data example
Image popup on page load using HTML and jQuery
Ajax live data search using jQuery PHP MySQL
jQuery loop over JSON result after AJAX Success
Simple star rating system using PHP, jQuery and Ajax
jquery image zoom on mouseover example
Bootstrap star rating input example
Bootstrap datepicker example
Submit a form data without page refresh