Move an array element from one array position to another

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

    I ended up combining two of these to work a little better when moving both small and large distances. I get fairly consistent results, but this could probably be tweaked a little bit by someone smarter than me to work differently for different sizes, etc.

    Using some of the other methods when moving objects small distances was significantly faster (x10) than using splice. This might change depending on the array lengths though, but it is true for large arrays.

    function ArrayMove(array, from, to) {
        if ( Math.abs(from - to) > 60) {
            array.splice(to, 0, array.splice(from, 1)[0]);
        } else {
            // works better when we are not moving things very far
            var target = array[from];
            var inc = (to - from) / Math.abs(to - from);
            var current = from;
            for (; current != to; current += inc) {
                array[current] = array[current + inc];
            }
            array[to] = target;    
        }
    }
    

    http://jsperf.com/arraymove-many-sizes

提交回复
热议问题