0

This is my code to remove an element from an array using "shifting method" :

// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;

contract Arrayelement{ //context : /* let an array be : [1,2,3,4] .... we want to remove 2 what we do is , shift elements startng from 2 towards left i.e. the array will become [1,3,4,4] and then pop out last 4 */

uint[] public arr;

function remove(uint _index) public {
    require(_index < arr.length, "Index out of bounds");
    for(uint i = _index ; i < arr.length-1; i++){
        arr[i] = arr[i+1];
    }
    arr.pop();
}

function testremove() public {
    arr = [1,2,3,4,5];
    remove(2);
    assert(arr[0] == 1);
    assert(arr[1] == 2);
    assert(arr[2] == 4);
    assert(arr[3] == 5);
    assert(arr.length == 4);
}

function get() public view {
       }

}

get() function is what I want to write so that I can see the results of the steps in the testremove() function.

alper
  • 8,395
  • 11
  • 63
  • 152
shikamaru
  • 17
  • 2

1 Answers1

0

You already have a an arr() function to inspect the array, one row at a time. This is the scalable pattern. You can also make a function that returns the whole array. Caution with that because it doesn't scale.

Not sure if this just a contrived example, or if there is a goal in mind. Have a look over here: Are there well-solved and simple storage patterns for Solidity?.

Deletion is a little counter-intuitive in blockchains. It often isn't needed and it is never completely effective. An additional challenge is to create a process that has the same cost at any scale which this iterative process does not achieve. This explainer unfolds a pattern with an example. The pattern is used in OpenZeppelin EnumerableSet.sol: https://medium.com/robhitchens/solidity-crud-part-1-824ffa69509a

Here's your getter:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;

contract Arrayelement{

uint[] public arr;

function set() public {
    for(uint i=0; i<10; i++) {
        arr.push(i+1);
    }
}

function get() public view returns(uint[] memory array) {
    return arr;
}

function remove(uint _index) public {
    require(_index < arr.length, "Index out of bounds");
    for(uint i = _index ; i < arr.length-1; i++){
        arr[i] = arr[i+1];
    }
    arr.pop();
}

}

Hope it helps.

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145