Understanding Array Slice() in JavaScript
Introduction
With the assistance of examples, we will learn about the JavaScript Array slice() technique in this article.
Slice() creates a new array object by making a shallow duplicate of a specific area of an array.
Example:
let numbers = [2, 3, 5, 7, 11, 13, 17]; // create another array by slicing numbers from index 3 to 5 let newArray = numbers.slice(3, 6); console.log(newArray); |
Output:
slice() Syntax
The slice() method's syntax is as follows:
arr.slice(start, end)
The array arr is used here.
slice() Constraints:
Slice() function includes:
- start (optional) - The selection's initial index. Unless otherwise specified, the selection begins at start 0.
- end (optional) - The selection's final index (exclusive). The selection stops at the final element's index if it is not given.
Return value for slice():
Returns a new array that contains the elements that were removed.
Examples
Example 1: The slice() function in JavaScript.
let languages = ["JavaScript", "Python", "C", "C++", "Java"]; // slicing the array (from start to end) let new_arr = languages.slice(); console.log(new_arr); // [ 'JavaScript', 'Python', 'C', 'C++', 'Java' ] // slicing from the third element let new_arr1 = languages.slice(2); console.log(new_arr1); // [ 'C', 'C++', 'Java' ] // slicing from the second element to fourth element let new_arr2 = languages.slice(1, 4); console.log(new_arr2); // [ 'Python', 'C', 'C++' ] |
Output:
Example 2: Negative index slice() in JavaScript
You may also use negative start and end indices with JavaScript. The final element's index is -1, the next-to-last element's index is -2, and so on.
const languages = ["JavaScript", "Python", "C", "C++", "Java"]; // slicing the array from start to second-to-last let new_arr = languages.slice(0, -1); console.log(new_arr); // [ 'JavaScript', 'Python', 'C', 'C++' ] // slicing the array from third-to-last let new_arr1 = languages.slice(-3); console.log(new_arr1); // [ 'C', 'C++', 'Java' ] |
Output:
Example 3: Objects as Array Elements in JavaScript's slice()
The array's elements are shallowly copied using the slice() function as follows:
- References to objects are copied to the new array. (For instance, a nested array) As a result, any modifications to the referenced object are reflected in the newly returned array.
- It duplicates the value of strings and numbers to the new array.
let human = { name: "David", age: 23, }; let arr = [human, "Nepal", "Manager"]; let new_arr = arr.slice(); // original object console.log(arr[0]); // { name: 'David', age: 23 } // making changes to the object in new array new_arr[0].name = "Levy"; // changes are reflected console.log(arr[0]); // { name: 'Levy', age: 23 } |
Output:
Hope this gave you a clear understanding of the concept. To check out more topics in Javascript, visit our Discussion Forum.