Move an array element from one array position to another

后端 未结 30 3050
渐次进展
渐次进展 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 08:58

    My 2c. Easy to read, it works, it's fast, it doesn't create new arrays.

    function move(array, from, to) {
      if( to === from ) return array;
    
      var target = array[from];                         
      var increment = to < from ? -1 : 1;
    
      for(var k = from; k != to; k += increment){
        array[k] = array[k + increment];
      }
      array[to] = target;
      return array;
    }
    

提交回复
热议问题