Move an array element from one array position to another

后端 未结 30 2956
渐次进展
渐次进展 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:59

    I needed an immutable move method (one that didn't change the original array), so I adapted @Reid's accepted answer to simply use Object.assign to create a copy of the array before doing the splice.

    Array.prototype.immutableMove = function (old_index, new_index) {
      var copy = Object.assign([], this);
      if (new_index >= copy.length) {
          var k = new_index - copy.length;
          while ((k--) + 1) {
              copy.push(undefined);
          }
      }
      copy.splice(new_index, 0, copy.splice(old_index, 1)[0]);
      return copy;
    };
    

    Here is a jsfiddle showing it in action.

提交回复
热议问题