Move an array element from one array position to another

后端 未结 30 2934
渐次进展
渐次进展 2020-11-22 08:36

I\'m having a hard time figuring out how to move an array element. For example, given the following:

var arr = [ \'a\', \'b\', \'c\', \'d\', \'e\'];
<         


        
30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 09:04

    One approach would be to create a new array with the pieces in the order you want, using the slice method.

    Example

    var arr = [ 'a', 'b', 'c', 'd', 'e'];
    var arr2 = arr.slice(0,1).concat( ['d'] ).concat( arr.slice(2,4) ).concat( arr.slice(4) );
    
    • arr.slice(0,1) gives you ['a']
    • arr.slice(2,4) gives you ['b', 'c']
    • arr.slice(4) gives you ['e']

提交回复
热议问题