Get n numbers from array starting from given point JavaScript


We have to write an array function (Array.prototype.get()) that takes in three arguments first, a number n, second is also a number, say m, (m <= array length-1) and second is a string that can have one of the two values − ‘left’ or ‘right’.

The function should return a subarray of the original array that should contain n elements starting from the index m, and in the specified direction like left or right.

For example −

// if the array is:
const arr = [0, 1, 2, 3, 4, 5, 6, 7];
// and the function call is:
arr.get(4, 6, 'right');
// then the output should be:
const output = [6, 7, 0, 1];

So, let’s write the code for this function −

Example

const arr = [0, 1, 2, 3, 4, 5, 6, 7];
Array.prototype.get = function(num, ind, direction){
   const amount = direction === 'left' ? -1 : 1;
   if(ind > this.length-1){
      return false;
   };
   const res = [];
   for(let i = ind, j = 0; j < num; i += amount, j++){
      if(i > this.length-1){
         i = i % this.length;
      };
      if(i < 0){
         i = this.length-1;
      };
      res.push(this[i]);
   };
   return res;
};
console.log(arr.get(4, 6, 'right'));
console.log(arr.get(9, 6, 'left'));

Output

The output in the console will be −

[ 6, 7, 0, 1 ]
[
   6, 5, 4, 3, 2,
   1, 0, 7, 6
]

Updated on: 28-Aug-2020

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements