How to slice an array with wrapping in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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
]
raja
Published on 20-Aug-2020 10:05:02
Advertisements