Move an array element from one array position to another

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

    Here is my one liner ES6 solution with an optional parameter on.

    if (typeof Array.prototype.move === "undefined") {
      Array.prototype.move = function(from, to, on = 1) {
        this.splice(to, 0, ...this.splice(from, on))
      }
    }
    

    Adaptation of the first solution proposed by digiguru

    The parameter on is the number of element starting from from you want to move.

提交回复
热议问题