2

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;

2 Answers 2

2

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
}
1
  • 1
    I think the return must be an int256 instead uint256 because the negative signed number in case of not found ( -1 ) and if (array[i] == searchFor) must be if (arr[i] == searchFor) Commented Mar 8, 2022 at 9:25
1

So, Lauri's answer was kind of correct, but array should be arr on line 3 and an unsigned int can never be -1 so I would rather revert on that line. Code should look like:

function indexOf(uint256[] memory arr, uint256 searchFor) private pure returns (uint256) {
    for (uint256 i = 0; i < arr.length; i++) {
      if (arr[i] == searchFor) {
        return i;
      }
    }
    revert("Not Found");
  }
1
  • reverting because a simple <array>.indexOf search found no match sounds insane to me. That would be even worse than the Javascript version of <array>.indexOf throwing an Error because the search found no match. Commented Apr 11 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.