Move an array element from one array position to another

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

    This version isn't ideal for all purposes, and not everyone likes comma expressions, but here's a one-liner that's a pure expression, creating a fresh copy:

    const move = (from, to, ...a) => (a.splice(to, 0, ...a.splice(from, 1)), a)
    

    A slightly performance-improved version returns the input array if no move is needed, it's still OK for immutable use, as the array won't change, and it's still a pure expression:

    const move = (from, to, ...a) => 
        from === to 
        ? a 
        : (a.splice(to, 0, ...a.splice(from, 1)), a)
    

    The invocation of either is

    const shuffled = move(fromIndex, toIndex, ...list)
    

    i.e. it relies on spreading to generate a fresh copy. Using a fixed arity 3 move would jeopardize either the single expression property, or the non-destructive nature, or the performance benefit of splice. Again, it's more of an example that meets some criteria than a suggestion for production use.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 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
        };
    
    0 讨论(0)
  • 2020-11-22 08:48
    let ar = ['a', 'b', 'c', 'd'];
    
    function change( old_array, old_index , new_index ){
    
      return old_array.map(( item , index, array )=>{
        if( index === old_index ) return array[ new_index ];
        else if( index === new_index ) return array[ old_index ];
        else return item;
      });
    
    }
    
    let result = change( ar, 0, 1 );
    
    console.log( result );
    

    result:

    ["b", "a", "c", "d"]
    
    0 讨论(0)
  • 2020-11-22 08:48

    This method will preserve the original array, and check for bounding errors.

    const move = (from, to, arr) => {
        to = Math.max(to,0)
        from > to 
            ? [].concat(
                arr.slice(0,to), 
                arr[from], 
                arr.filter((x,i) => i != from).slice(to)) 
            : to > from
                ? [].concat(
                    arr.slice(0, from), 
                    arr.slice(from + 1, to + 1), 
                    arr[from], 
                    arr.slice(to + 1))
                : arr}
    
    0 讨论(0)
  • 2020-11-22 08:51

    The splice() method adds/removes items to/from an array, and returns the removed item(s).

    Note: This method changes the original array. /w3schools/

    Array.prototype.move = function(from,to){
      this.splice(to,0,this.splice(from,1)[0]);
      return this;
    };
    
    var arr = [ 'a', 'b', 'c', 'd', 'e'];
    arr.move(3,1);//["a", "d", "b", "c", "e"]
    
    
    var arr = [ 'a', 'b', 'c', 'd', 'e'];
    arr.move(0,2);//["b", "c", "a", "d", "e"]
    

    as the function is chainable this works too:

    alert(arr.move(0,2).join(','));
    

    demo here

    0 讨论(0)
提交回复
热议问题