Move an array element from one array position to another

后端 未结 30 2542
渐次进展
渐次进展 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条回答
  •  旧时难觅i
    2020-11-22 08:53

    You can implement some basic Calculus and create a universal function for moving array element from one position to the other.

    For JavaScript it looks like this:

    function magicFunction (targetArray, indexFrom, indexTo) { 
    
        targetElement = targetArray[indexFrom]; 
        magicIncrement = (indexTo - indexFrom) / Math.abs (indexTo - indexFrom); 
    
        for (Element = indexFrom; Element != indexTo; Element += magicIncrement){ 
            targetArray[Element] = targetArray[Element + magicIncrement]; 
        } 
    
        targetArray[indexTo] = targetElement; 
    
    }
    

    Check out "moving array elements" at "gloommatter" for detailed explanation.

    http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html

提交回复
热议问题