简体   繁体   中英

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, eg it can be 1 element only or more than 2.

Please help me.

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} 

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); 

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); 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM