raju
raju

Reputation: 6946

moving multiple elements in an array javascript

I have an array ["a","b","c","d","e"].

I want to move element index 1,2 to move one step up/down in the order so that new array would be ["b","c","d","e","a"].

If it is single element only, I can do that, but I could not figure out, how to do that in JavaScript.

The number of index elements to be moved can be any, e.g. it can be 1 element only or more than 2.

Please help me.

Upvotes: 0

Views: 4864

Answers (4)

Faly
Faly

Reputation: 13356

You can use array.prototype.unshift, array.prototype.push and array.prototype.splice:

var arr = ["a","b","c","d","e"];
function rotateRight(arr, nb) {
    var rightPart = arr.splice(arr.length - nb, arr.length);
    arr.unshift(...rightPart);
}

function rotateLeft(arr, nb) {
    var leftPart = arr.splice(0, nb);
    arr.push(...leftPart);        
}

rotateRight(arr, 3);
console.log(arr);
rotateLeft(arr, 3);
console.log(arr);

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68433

Use push and splice ()

var noOfItems = 2;
arr.push.apply( arr, arr.splice( 0, noOfItems ) );

Demo

var arr = ["a","b","c","d","e"]
var noOfItems = 2;
arr.push.apply( arr, arr.splice( 0, noOfItems ) );
console.log(arr);

Or if you want to do the reverse, then use unshift

arr.unshift( arr.pop()  )

And for multiple elements

arr.unshift.apply( arr, arr.splice(-2)  )

Demo

var arr = ["a","b","c","d","e"]
var noOfItems = 2;
arr.unshift.apply( arr, arr.splice( -noOfItems )  )
console.log(arr);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386816

You could shift and push the element.

const
    down = array => array.push(array.shift()),
    up = array => array.unshift(array.pop());

var array = ["a", "b", "c", "d", "e"];

up(array);
console.log(array);

down(array);
console.log(array);

Upvotes: 0

Thomas
Thomas

Reputation: 12667

A little function if you want to move the indices by an arbitrary offset.

//returns a new array with the items shifted
function move(arr, offset=0){
  //positive offsets move right
  const pivot = (offset < 0? 0: arr.length) - offset % arr.length;
  //positive offsets move left
  //const pivot = (offset < 0? arr.length: 0) + offset % arr.length;
  return arr.slice(pivot).concat(arr.slice(0, pivot));
}

let arr = ["a","b","c","d","e","f"];
for(let i=-5; i<10; ++i){
  console.log("shifted by %i %s", i, move(arr, i));
}
.as-console-wrapper{top:0;max-height:100%!important}

Upvotes: 1

Related Questions