Move an array element from one array position to another

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

    It is stated in many places (adding custom functions into Array.prototype) playing with the Array prototype could be a bad idea, anyway I combined the best from various posts, I came with this, using modern Javascript:

        Object.defineProperty(Array.prototype, 'immutableMove', {
            enumerable: false,
            value: 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
            }
        });
    
        //how to use it
        myArray=[0, 1, 2, 3, 4];
        myArray=myArray.immutableMove(2, 4);
        console.log(myArray);
        //result: 0, 1, 3, 4, 2
    

    Hope can be useful to anyone

提交回复
热议问题