Different Ways to Use Array Slice in JavaScript
Last Updated :
05 Oct, 2023
In this article, we will see the different ways to use the Array slice method in Javascript. Using Array Slice in JavaScript refers to the technique of extracting a specified portion of an array, defined by start and end indices, to create a new array containing those selected elements.
Syntax
arr.slice(begin, end);
Parameters: This method accepts two parameters as mentioned above and described below:
- begin: This parameter defines the starting index from where the portion is to be extracted. If this argument is missing then the method takes begin as 0 as it is the default start value.
- end: This parameter is the index up to which the portion is to be extracted (excluding the end index). If this argument is not defined then the array till the end is extracted as it is the default end value If the end value is greater than the length of the array, then the end value changes to the length of the array.
Return value: This method returns a new array containing some portion of the original array.
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using to copy an array
The slice() method can be used to create a copy of an array.to copy an array, use slice() method with no arguments, creating a shallow copy that duplicates the entire array without modifying the original.
Example: In this example we are using the above-explained apporach.
JavaScript
let languages = ["HTML", "CSS", "JavaScript", "React.js"];
console.log("orignal array :", languages)
let copiedArray = languages.slice();
console.log("Copied array :", copiedArray);
Outputorignal array : [ 'HTML', 'CSS', 'JavaScript', 'React.js' ]
Copied array : [ 'HTML', 'CSS', 'JavaScript', 'React.js' ]
Approach 2: To get the first N elements of an array
The slice() method can be used to get the first N elements of an array. To get the first N elements of an array, use slice(0, N), specifying the start index as 0 and the end index as N to extract the desired portion.
Example: In this example we are using the above-explained apporach.
JavaScript
let languages = ["HTML", "CSS", "JavaScript", "React.js"];
console.log("orignal array :", languages)
let result = languages.slice(0, 2);
console.log("Sliced array :", result);
Outputorignal array : [ 'HTML', 'CSS', 'JavaScript', 'React.js' ]
Sliced array : [ 'HTML', 'CSS' ]
Approach 3: Using to remove elements at specific index
The slice() method can be used to remove elements at specific index. To remove elements at a specific index, use slice(0, index).concat(arr.slice(index + 1)). It extracts elements before and after the index, effectively excluding the desired element.
Example: In this example we are using the above-explained apporach.
JavaScript
let arr = ["HTML", "CSS", "JavaScript", "React.js"];
// Remove the element at index 2 (value 3)
let indexToRemove = 2;
let newArr = arr.slice(0, indexToRemove).concat(
arr.slice(indexToRemove + 1));
console.log("Original Array:", arr);
console.log("New Array:", newArr);
OutputOriginal Array: [ 'HTML', 'CSS', 'JavaScript', 'React.js' ]
New Array: [ 'HTML', 'CSS', 'React.js' ]
To extract a range of elements from an array, use the slice(startIndex, endIndex) method. It creates a new array with elements from startIndex (inclusive) to endIndex (exclusive) in the original array.
Example: In this example we are using the above-explained apporach.
JavaScript
let languages = ["HTML", "CSS", "JavaScript", "React.js"];
console.log("orignal array :", languages)
let result = languages.slice(1, 3);
console.log("new array :", result);
Outputorignal array : [ 'HTML', 'CSS', 'JavaScript', 'React.js' ]
new array : [ 'CSS', 'JavaScript' ]
Similar Reads
Fastest way to duplicate an array in JavaScript Multiple methods can be used to duplicate an array in JavaScript.The fastest way to duplicate an array in JavaScript is by using the slice() Method. Let us discuss some methods and then compare the speed of execution. The methods to copy an array are: Table of Content Using slice() Using concat() me
4 min read
What is the difference between Array.slice() and Array.splice() in JavaScript ? In JavaScript, slice() and splice() are array methods with distinct purposes. `slice()` creates a new array containing selected elements from the original, while `splice()` modifies the original array by adding, removing, or replacing elements. slice():The slice() method in JavaScript extracts a sec
3 min read
JavaScript arrayBuffer slice() Method The arrayBuffer.slice is a property in JavaScript that return another arrayBuffer containing the contents of the previous arrayBuffer from beginning inclusive, to end, exclusive in bytes. ArrayBuffer is an object which is used to represent fixed-length binary data. Difference between property and fu
2 min read
Difference between String.slice and String.substring in JavaScript These 2 functions are quite similar in their Syntax But are different in some cases. Let's see the difference between them. JavaScript slice() Method:This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted par
3 min read
Important Array Methods of JavaScript JavaScript arrays are powerful tools for managing collections of data. They come with a wide range of built-in methods that allow developers to manipulate, transform, and interact with array elements.Some of the most important array methods in JavaScript areTable of Content1. JavaScript push() Metho
7 min read
JavaScript - Convert String to Array Strings in JavaScript are immutable (cannot be changed directly). However, arrays are mutable, allowing you to perform operations such as adding, removing, or modifying elements. Converting a string to an array makes it easier to:Access individual characters or substrings.Perform array operations su
5 min read
How to Declare an Array in JavaScript? Array in JavaScript are used to store multiple values in a single variable. It can contain any type of data like - numbers, strings, booleans, objects, etc. There are varous ways to declare arrays in JavaScript, but the simplest and common is Array Litral Notations. Using Array Literal NotationThe b
3 min read
JavaScript Array entries() Method The entries() method in JavaScript is used to create an iterator that returns key/value pairs for each index in the array.It allows iterating over arrays and accessing both the index and value of each element sequentially.Syntax:array.entries()Parameters:This method does not accept any parameters.Re
3 min read
Types of Arrays in JavaScript A JavaScript array is a collection of multiple values at different memory blocks but with the same name. The values stored in an array can be accessed by specifying the indexes inside the square brackets starting from 0 and going to the array length - 1([0]...[n-1]). A JavaScript array can be classi
3 min read
Split an Array into Chunks in JavaScript Here are different methods to split an array into chunks in JavaScript.1. Using slice() MethodThe array slice() method returns a new array containing the selected elements. This method selects the elements starting from the given start argument and ends at, but excluding the given end argument. Synt
3 min read