Move an array element from one array position to another

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

    This is based on @Reid's solution. Except:

    • I'm not changing the Array prototype.
    • Moving an item out of bounds to the right does not create undefined items, it just moves the item to the right-most position.

    Function:

    function move(array, oldIndex, newIndex) {
        if (newIndex >= array.length) {
            newIndex = array.length - 1;
        }
        array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
        return array;
    }
    

    Unit tests:

    describe('ArrayHelper', function () {
        it('Move right', function () {
            let array = [1, 2, 3];
            arrayHelper.move(array, 0, 1);
            assert.equal(array[0], 2);
            assert.equal(array[1], 1);
            assert.equal(array[2], 3);
        })
        it('Move left', function () {
            let array = [1, 2, 3];
            arrayHelper.move(array, 1, 0);
            assert.equal(array[0], 2);
            assert.equal(array[1], 1);
            assert.equal(array[2], 3);
        });
        it('Move out of bounds to the left', function () {
            let array = [1, 2, 3];
            arrayHelper.move(array, 1, -2);
            assert.equal(array[0], 2);
            assert.equal(array[1], 1);
            assert.equal(array[2], 3);
        });
        it('Move out of bounds to the right', function () {
            let array = [1, 2, 3];
            arrayHelper.move(array, 1, 4);
            assert.equal(array[0], 1);
            assert.equal(array[1], 3);
            assert.equal(array[2], 2);
        });
    });
    

提交回复
热议问题