I am trying to rotate an array according to the user input, I want to take the array from the user and number of positions to shift from, from the user, and the direction to shift in i.e., left or right from the user(which can be taken as 0 for left and 1 for right) So far I could do this
const numList = [1, 2, 3, 4, 5, 6]
const p = 3
function changeArray(arr, shift) {
for (let i = 0; i < shift; i ) {
arr.unshift(arr.pop())
console.log(`${i 1}:`, arr)
}
}
console.log(changeArray(numList, p))
I am doing this to take inputs from user:
const numList= prompt("Type your array")
const p=prompt("Type your position")
Please tell me how can I take the input from the user.
this gives me the expected output but I want to take the inputs from user and when I try that it says, arr.pop()
is not a function. I also couldn't add the direction functionality to it, could anyone tell me what can be done here?
CodePudding user response:
const n = prompt("Type your array").split(',');
const p = prompt("Amount to rotate by?");
const d = prompt("Direction? L/R").toUpperCase().includes('L') ? -1 : 1;
console.log(n.map((_,i,a)=> a[(a.length i-(p%a.length*d))%a.length]));
CodePudding user response:
You can achieve this using array.slice
Idea:
Array.slice
takes negative numbers which will return ending n numbers. You create a new list starting these numbers- Call
Array.slice
again but from starting position (0) and uselength - n
to get remaining numbers
Also, its better to not mutate an same array that you are looping on. pop
will change the length and so will unshift
. It can have weird outcome. Using a new array is better and works with immutability concept as well
const rotateArr = (arr, p, direction) => {
if (direction === "left")
return [
...arr.slice(-1 * p),
...arr.slice(0, arr.length - p)
]
else
return [
...arr.slice(p),
...arr.slice(0, p)
]
}
const data = prompt("Enter comma seperated values")
.split(",")
.map(Number)
const position = Number(prompt("Enter Position to shift"))
const direction = prompt("Enter the direction? Left or Right")
console.log(rotateArr(data, position, direction))