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
Different Ways to Crate an Array of Objects in JavaScript ?
Objects in JavaScript are key-value pairs, making them suitable for representing structured data. Also, an array in JavaScript is a versatile data structure that can hold a collection of values. When dealing with objects, an array can be used to store multiple objects. An array of objects allows you
3 min read
JavaScript Array Iteration Methods
JavaScript Array iteration methods perform some operation on each element of an array. Array iteration means accessing each element of an array. There are some examples of Array iteration methods are given below: Using Array forEach() MethodUsing Array some() MethodUsing Array map() MethodMethod 1:
3 min read
Convert Array to String in JavaScript
In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use differen
7 min read
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
Set vs Array in JavaScript
In JavaScript, Set and Array are common data structures used to store collections of data. These data structures are different because of their unique features. Let us look at the implementation of both of these data structures. JavaScript SetSets are used to store collections of unique value withou
2 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
Array vs. Object Efficiency in JavaScript
In JavaScript, both arrays and objects are used for storing data, but they are suited for different use cases. Understanding their efficiency is key to choosing the right data structure for your application.If you want to know the full comparison between arrays and objects, click here.Use Cases for
2 min read
How to fill static values in an array in JavaScript ?
In this article, we will see the methods to fill an array with some static values. There are many ways to fill static values in an array in JavaScript such as: Using Array fill() MethodUsing for loopUsing push() methodUsing from() methodUsing spread operatorMethod 1: Array fill() Method We use the a
5 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
Fastest way to convert JavaScript NodeList to Array
There are many ways to convert a NodeList to a JavaScript array but the fastest of all is a new method from ES6. In ES6, we can now simply create an Array from a NodeList using the Array.from() method. ApproachThe JavaScript Array.from() method is used to create a new array instance from a given arr
2 min read