Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get n numbers from array starting from given point JavaScript
We need to create a custom Array method that extracts n elements from an array starting at a given index, moving in a specified direction (left or right). When we reach array boundaries, the function wraps around to continue from the other end.
Problem Requirements
The function should take three parameters:
- n - number of elements to extract
- m - starting index (must be ? array.length - 1)
- direction - either 'left' or 'right'
For example, if we have [0, 1, 2, 3, 4, 5, 6, 7] and call get(4, 6, 'right'), it should return [6, 7, 0, 1] by wrapping around when it reaches the end.
Implementation
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("Moving right from index 6:", arr.get(4, 6, 'right'));
console.log("Moving left from index 6:", arr.get(9, 6, 'left'));
Moving right from index 6: [ 6, 7, 0, 1 ] Moving left from index 6: [ 6, 5, 4, 3, 2, 1, 0, 7, 6 ]
How It Works
The function uses a direction multiplier (amount) to determine movement: -1 for left, +1 for right. When the index goes beyond array bounds, it wraps around using modulo for forward movement or resets to the last index for backward movement.
Example Breakdown
const testArr = [0, 1, 2, 3, 4, 5, 6, 7];
// Right direction: starts at index 6, gets 4 elements
console.log("Right from 6:", testArr.get(4, 6, 'right'));
// [6, 7, 0, 1] - wraps to beginning after reaching end
// Left direction: starts at index 3, gets 5 elements
console.log("Left from 3:", testArr.get(5, 3, 'left'));
// [3, 2, 1, 0, 7] - wraps to end after reaching beginning
Right from 6: [ 6, 7, 0, 1 ] Left from 3: [ 3, 2, 1, 0, 7 ]
Conclusion
This custom Array method enables circular extraction of elements in both directions. The wrapping behavior makes it useful for scenarios requiring continuous data access beyond array boundaries.
