1

I have an array with elements. for ex - let data = [ 1, 2, 3, 4, 5 ];

Now if I pass 2 in function as a parameter, then the last two value will move to first in the array.

 let data = [1, 2, 3, 4, 5];
 functionname(data, 2);
 //Expected output - 4,5,1,2,3

Now if I pass 3 in function as a parameter, then the last three value will move to first in the array.

  let data = [ 1, 2, 3, 4, 5 ];
    functionname(data, 3);
    //Expected output - 3,4,5,1,2
9
  • 2
    What's the problem with your code? Commented Nov 20, 2019 at 12:16
  • @FelixKling Problem is , current code is not giving expected output. Commented Nov 20, 2019 at 12:20
  • 2
    BTW,You have 3 arguments in your function and only 2 are given in your call. Commented Nov 20, 2019 at 12:20
  • 1
    Why do you expect the first call to move two values (4 and 5) to the front ? Commented Nov 20, 2019 at 12:22
  • 1
    Even with the updated requirements the expected output for the second call is wrong. Moving the last 3 values of 4,5,1,2,3 to the front will result in 1,2,3,4,5. Commented Nov 20, 2019 at 12:30

3 Answers 3

2

Immutable

function insertAndShift(arr, from) {
    return [...arr.slice(-from), ...arr.slice(0, arr.length - from)];
}
insertAndShift([1,2,3,4,5], 2) // [4, 5, 1, 2, 3]
insertAndShift([1,2,3,4,5], 3); // [3, 4, 5, 1, 2]
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. However on defense of my answer - if you check history of this question you will find out it looked like mutability were required.
0

function insertAndShift(data, len) 
{
    let cutOut = data.splice(-len);         // cut <len> elements from the end
    data.splice(0, 0, ...cutOut);           // insert it at index 0
}
    
let data = [1,2,3,4,5];
insertAndShift(data, 2);
console.log(data);

data = [1,2,3,4,5];
insertAndShift(data, 3);
console.log(data);

Comments

0

Here you are

function insertAndShift(arr, from) {
        let cutOut = arr.splice(arr.length - from, arr.length); 
        arr.splice(0, 0, ...cutOut);            
    }
    
let data = [ 1, 2, 3, 4, 5];

insertAndShift(data, 2)
console.log(data)

data = [ 1, 2, 3, 4, 5];
insertAndShift(data, 3)
console.log(data)

2 Comments

second argument of splice method is number of element you would like to cut, not the last index
@l00k fixed. so it cuts and shifts last from number of values to the begning

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.