Find out the power of the JavaScript Array slice() method with this comprehensive guide.
Discover five (5) practical ways to use slice() to manipulate arrays, from selecting elements to creating shallow copies.
With clear explanations and examples, this article covers everything you need to know to master the slice() method and enhance your JavaScript skills to the next level.
What is JavaScript array slice?
The array.slice() method in JavaScript is used to return a shallow copy of a portion of an array into a new array object selected from start to end (end not included).
Where start and end represent the index of items in that array. The original array will not be changed.
Syntax
The basic syntax for JavaScript array.slice() method is as follows:
slice() ✅
slice(start) ✅
slice(start, end) ✅
Parameter
📌start (Optional)
Zero-based index at which to start extraction. A negative index counts back from the end of the array. If the start is omitted, 0 is used.
📌end (Optional)
Zero-based index at which to end extraction. slice() extracts up to but not including the end. A negative index counts back from the end of the array.
If the “end” is not specified, the extraction process will utilize array.length, resulting in the extraction of all elements until the end.
Return value
This method returns a new array containing the extracted or selected elements.
How to use JavaScript Array Slice() method?
Here are 5 ways you can use the JavaScript Array.slice() method:
Select elements
You can use the slice() method to select elements from an array.
For example, if you have an array of subjects and you want to select the subjects that contain math, you can use the slice() method like this:
const subjects = ["English", "Algebra", " Programming", "Science", "History"];
const math = subjects.slice(1, 3);
console.log(math);
This code will create a new array called math that contains the elements “Algebra” and “Programming.”
Output:
[ 'Algebra', ' Programming' ]
Select elements using negative values
You can also use negative values as arguments for the slice() method to select elements from the end of the array.
For example, if you want to select the last three elements of an array of subjects, you can use the slice() method like this:
const subjects = ["English", "Algebra", " Programming", "Science", "History"];
const myfav = subjects.slice(-3);
console.log(myfav);
Output:
[ ' Programming', 'Science', 'History' ]
Return a portion of an existing array
You can use the slice() method to return a portion of an existing array.
For example, if you have an array of subjects and you want to create a new array that contains only the first two elements, you can use the slice() method like this:
const subjects = ["English", "Algebra", " Programming", "Science", "History"];
const newsubjects = subjects.slice(0, 2);
console.log(newsubjects);
Output:
[ 'English', 'Algebra' ]
Using slice on a nested array
You can use the slice() method on a nested array as well.
For example, if you have a nested array of numbers and you want to create a new array that contains only the second and third sub-arrays, you can use the slice() method like this:
var samplenestedArray = [[10, 20, 30], [40, 50, 60], [70, 80, 90]];
var newsamplenestedArray = samplenestedArray.slice(1, 3);
console.log(newsamplenestedArray);
Output:
[ [ 40, 50, 60 ], [ 70, 80, 90 ] ]
Create a shallow copy of an array
You can use the slice() method to create a shallow copy of an array.
It means that if you have an array that contains objects or other arrays as elements, those objects or arrays will be copied by reference rather than by value.
Here’s an example:
const mySubject = { name: "Programming", teacher: "Mr. Smith", students: 20, room: 1 };
const mySchedule = [mySubject, 2, "Monday", "8:00 AM"];
const newSchedule = mySchedule.slice(0, 2);
console.log(newSchedule); // [{...}, 2]
Output:
[ { name: 'Math', teacher: 'Ms. Smith', students: 30, room: 101 }, 2 ]
In our example the 2 in the last part of the code refers to the second element of the mySchedule array. The mySchedule array is defined as follows:
const mySchedule = [mySubject, 2, "Monday", "8:00 AM"];
The second element of this array is the number 2, which represents the second period of the day when the subject takes place.
When we use the slice() method to create a new array newSchedule that is a shallow copy of the first two elements of the mySchedule array, we are including both the mySubject object and the number 2 in the new array.
Here’s the relevant code:
const newSchedule = mySchedule.slice(0, 2);
console.log(newSchedule);
The newSchedule array contains a reference to the same mySubject object as well as the number 2, which is logged to the console.
Frequently Asked Questions (FAQs)
What does array slice () do?
The JavaScript array.slice() method is used to return a shallow copy of a portion of an array into a new array object selected from start to end (end not included), where start and end represent the index of items in that array.
Can you slice an array in JavaScript?
Yes, you can use the slice() method to slice an array in JavaScript. For instance, if you have an array of numbers and you want to create a new array that contains only the first three elements, you can use the slice() method like this:
const numbers = [10, 20, 30, 40, 50];
const newNumbers = numbers.slice(0, 3);
console.log(newNumbers);
Output:
[ 10, 20, 30 ]
What is array slice (- 1)?
When you use a negative value as an argument for the slice() method, it counts back from the end of the array.
For instance, if you use an array.slice(-1), it will return a new array containing only the last element of the original array.
Here’s an example:
const numbers = [10, 20, 30, 40, 50];
const lastNumber = numbers.slice(-1);
console.log(lastNumber);
Output:
[ 50 ]
Conclusion
In conclusion, the article discusses the power of the JavaScript Array slice() method. That includes the syntax, parameters, and return value of the method.
Also, this article presents five practical ways to use slice() for array manipulation, including selecting elements, working with negative values, returning portions of arrays, using slice() on nested arrays, and creating shallow copies of arrays.
Through clear explanations and examples, you can enhance your JavaScript skills and master the slice() method effectively.
We are hoping that this article provides you with enough information that helps you understand the JavaScript array slice.
You can also check out the following article:
Thank you for reading itsourcecoders 😊.