![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to slice an array with wrapping in JavaScript
Let’s say, we are required to write an array method that overwrites the default Array.prototype.slice(). Usually the Array.prototype.slice() method takes in two arguments the start index and the end index, and returns a subarray of the original array from index start to end-1.
What we wish to do is make this slice() function like so it returns a subarray from index start to end and not end-1. Therefore, the code for doing this is shown below. We iterate over the array using a for loop which is in fact is faster than any of the array methods we have. Then return the required subarray, lastly we overwrite the Array.prototype.slice() with the method we just wrote −
Example
const arr = [5, 5, 34, 43, 43, 76, 78, 3, 23, 1, 65, 87, 9]; const slice = function(start = 0, end = this.length-1){ const part = []; for(let i = start; i <= end; i++){ part.push(this[i]); }; return part; }; Array.prototype.slice = slice; console.log(arr.slice(0, 4)); console.log(arr.slice(5, 8)); console.log(arr.slice());
Output
The output in the console will be −
[ 5, 5, 34, 43, 43 ] [ 76, 78, 3, 23 ] [ 5, 5, 34, 43, 43, 76, 78, 3, 23, 1, 65, 87, 9 ]
Advertisements