How to shift data from one position to another position in array using js

 To do this we need to use Array.prototype.copyWithin() method.

This method will shallow copy part of an array to another location in the same array without changing the length of the array. It takes 3 parameters, target, start, end.

  • Target is the position where the copied items will go.
  • Start is the starting index where the copying starts.
  • End is the end index where the copying ends.

More detailed information can be found here.

Example:


let arr = ["apple","strawberry","banana","cherry","tomato","carrot","plum",];


// copies the 3rd item to the zero'th position ie: the first position, the previous first
// element will be overwritten
console.log(arr.copyWithin(0, 3, 4));
// [ 'cherry','strawberry','banana','cherry','tomato','carrot','plum']

// copies the 3rd and 4th item to the zero'th position ie: the first position, the
// previous first element will be overwritten
console.log(arr.copyWithin(0, 3, 5));
// ['cherry', 'tomato','banana', 'cherry','tomato', 'carrot','plum' ]

 


Comments