Move an array element from one array position to another

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

    Got this idea from @Reid of pushing something in the place of the item that is supposed to be moved to keep the array size constant. That does simplify calculations. Also, pushing an empty object has the added benefits of being able to search for it uniquely later on. This works because two objects are not equal until they are referring to the same object.

    ({}) == ({}); // false
    

    So here's the function which takes in the source array, and the source, destination indexes. You could add it to the Array.prototype if needed.

    function moveObjectAtIndex(array, sourceIndex, destIndex) {
        var placeholder = {};
        // remove the object from its initial position and
        // plant the placeholder object in its place to
        // keep the array length constant
        var objectToMove = array.splice(sourceIndex, 1, placeholder)[0];
        // place the object in the desired position
        array.splice(destIndex, 0, objectToMove);
        // take out the temporary object
        array.splice(array.indexOf(placeholder), 1);
    }
    

提交回复
热议问题