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
Sai
  • 53
  • 1
  • 5

3 Answers3

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]
Dipak Telangre
  • 1,792
  • 4
  • 19
  • 46
  • Nice. However on defense of my answer - if you check history of this question you will find out it looked like mutability were required. – l00k Nov 20 '19 at 13:51
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);
l00k
  • 1,525
  • 1
  • 19
  • 29
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)
alireza
  • 518
  • 5
  • 15