Move an array element from one array position to another

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

    Here's a one liner I found on JSPerf....

    Array.prototype.move = function(from, to) {
        this.splice(to, 0, this.splice(from, 1)[0]);
    };
    

    which is awesome to read, but if you want performance (in small data sets) try...

     Array.prototype.move2 = function(pos1, pos2) {
        // local variables
        var i, tmp;
        // cast input parameters to integers
        pos1 = parseInt(pos1, 10);
        pos2 = parseInt(pos2, 10);
        // if positions are different and inside array
        if (pos1 !== pos2 && 0 <= pos1 && pos1 <= this.length && 0 <= pos2 && pos2 <= this.length) {
          // save element from position 1
          tmp = this[pos1];
          // move element down and shift other elements up
          if (pos1 < pos2) {
            for (i = pos1; i < pos2; i++) {
              this[i] = this[i + 1];
            }
          }
          // move element up and shift other elements down
          else {
            for (i = pos1; i > pos2; i--) {
              this[i] = this[i - 1];
            }
          }
          // put element from position 1 to destination
          this[pos2] = tmp;
        }
      }
    

    I can't take any credit, it should all go to Richard Scarrott. It beats the splice based method for smaller data sets in this performance test. It is however significantly slower on larger data sets as Darwayne points out.

提交回复
热议问题