Move an array element from one array position to another

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

    I used the nice answer of @Reid, but struggled with moving an element from the end of an array one step further - to the beginning (like in a loop). E.g. ['a', 'b', 'c'] should become ['c', 'a', 'b'] by calling .move(2,3)

    I achieved this by changing the case for new_index >= this.length.

    Array.prototype.move = function (old_index, new_index) {
            console.log(old_index + " " + new_index);
            while (old_index < 0) {
                old_index += this.length;
            }
            while (new_index < 0) {
                new_index += this.length;
            }
            if (new_index >= this.length) {
                new_index = new_index % this.length;
            }
            this.splice(new_index, 0, this.splice(old_index, 1)[0]);
            return this; // for testing purposes
        };
    

提交回复
热议问题