solidity – How to Implement indexOf Function in Solidity for Efficient Searches

arrayscontract-developmentsolidity

In javascript, can use indexOf to get the index of the value.

const array = [2, 5, 9];
const index = array.indexOf(5); 

How to implement it in solidity? I'll get the value from another function, and I want to use that value to find the index in an array(_R2), then delete that value.

uint256[] internal _R2;

Best Answer

You simply have to loop over the values to find the one you are searching for.

Something like this:

function indexOf(uint256[] memory arr, uint256 searchFor) private returns (uint256) {
  for (uint256 i = 0; i < arr.length; i++) {
    if (arr[i] == searchFor) {
      return i;
    }
  }
  return -1; // not found
}
Related Topic