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
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read