Skip to content

Commit 14d06f4

Browse files
author
Prathamesh Mhatre
committed
Rotate given array by n
1 parent d18bcda commit 14d06f4

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

Array/rotate/rotate-array-by-n.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function rotateArrayByN(array,n,direction = 'right') {
2+
if(direction === 'right') {
3+
return array.slice(n, array.length).concat(array.slice(0, n));
4+
} else if (direction === 'left') {
5+
return array.slice(-n).concat(array.slice(0,array.length-n));
6+
} else {
7+
return array;
8+
}
9+
10+
}
11+
console.log(rotateArrayByN([1, 2, 3, 4, 5, 6, 7],2,'left'));
12+
/**
13+
console.log(rotateArrayByN([1, 2, 3, 4, 5, 6, 7],2));
14+
// Output [3, 4, 5, 6, 7, 1, 2]
15+
16+
console.log(rotateArrayByN([1, 2, 3, 4, 5, 6, 7],2,'left'));
17+
// Output [6, 7, 1, 2, 3, 4, 5]
18+
*/

0 commit comments

Comments
 (0)