Array Replace Last

Another way to remove array element while keeping the array without any gaps is to copy the last element into the slot to remove and then remove the last element. This technique is more gas efficient

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract ArrayReplaceLast {
    uint[] public arr = [1, 2, 3, 4];

    function remove(uint _index) external {
        // Move the last element into the place to delete
            arr[_index] = arr[arr.length - 1];
        // Remove the last element
            arr.pop();
    }
}

Last updated

Was this helpful?