Skip to content

Instantly share code, notes, and snippets.

@rzvl
Created March 20, 2022 22:37
Show Gist options
  • Save rzvl/04a86530f60d326c810c7c7f7b71ae3e to your computer and use it in GitHub Desktop.
Save rzvl/04a86530f60d326c810c7c7f7b71ae3e to your computer and use it in GitHub Desktop.
Remove an element by replacing last
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract ArrayReplaceLast {
uint[] public arr;
function remove(uint _index) public {
arr[_index] = arr[arr.length - 1];
arr.pop();
}
function test() external {
arr = [1, 2, 3, 4];
remove(1);
assert(arr[0] == 1);
assert(arr[1] == 4);
assert(arr[2] == 3);
assert(arr.length == 3);
arr = [3];
remove(0);
assert(arr.length == 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment