Move an array element from one array position to another

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

    Array.move.js

    Summary

    Moves elements within an array, returning an array containing the moved elements.

    Syntax

    array.move(index, howMany, toIndex);
    

    Parameters

    index: Index at which to move elements. If negative, index will start from the end.

    howMany: Number of elements to move from index.

    toIndex: Index of the array at which to place the moved elements. If negative, toIndex will start from the end.

    Usage

    array = ["a", "b", "c", "d", "e", "f", "g"];
    
    array.move(3, 2, 1); // returns ["d","e"]
    
    array; // returns ["a", "d", "e", "b", "c", "f", "g"]
    

    Polyfill

    Array.prototype.move || Object.defineProperty(Array.prototype, "move", {
        value: function (index, howMany, toIndex) {
            var
            array = this,
            index = parseInt(index) || 0,
            index = index < 0 ? array.length + index : index,
            toIndex = parseInt(toIndex) || 0,
            toIndex = toIndex < 0 ? array.length + toIndex : toIndex,
            toIndex = toIndex <= index ? toIndex : toIndex <= index + howMany ? index : toIndex - howMany,
            moved;
    
            array.splice.apply(array, [toIndex, 0].concat(moved = array.splice(index, howMany)));
    
            return moved;
        }
    });
    

提交回复
热议问题