Nested Arrays
Nested arrays are rarely used in practice, but we include them here for the sake of completeness.
Nested arrays, as the name suggests, refer to arrays that are contained within another array.
In this example, the function is receiving a rectangular grid.
contract ExampleContract {
function containsAThree(uint256[][] calldata nestedArray)
public
pure
returns (bool) {
for (uint256 i = 0; i < nestedArray.length; i++) {
for (uint256 j = 0; j < nestedArray[i].length; j++) {
if (nestedArray[i][j] == 3) {
return true;
}
}
}
return false;
}
}
Here it is running in remix.
You can also get a 1D array from a 2D array
contract ExampleContract {
// [[1,2],[3,4],[5,6]] becomes [1,2]
function getRow(uint256[][] calldata nestedArray)
public
pure
returns(uint256[] memory) {
return nestedArray[0];
}
}
To declare arrays of a fixed size, use the following syntax
contract ExampleContract {
// ACCEPTED: [[1,2],[3,4],[5,6]]
// REJECTED: [[1,2,3],[4,5,6]]
function fixedSize(uint256[2][3] calldata nestedArray)
public
pure
returns (uint256) {
return 0; // just for the sake of compilation
}
}
What may be confusing is that when you access a specific item in an array, the order may feel backward from other languages, but it makes sense if you think about it.
contract ExampleContract {
// ACCEPTED: [[1,2],[3,4],[5,6]] -> returns 6
function getLast(uint256[2][3] calldata nestedArray)
public
pure
returns (uint256) {
return nestedArray[2][1];
// nestedArray[2] -> [5,6] then get the 1st index item -> 6
}
}
Just like 1D arrays, if you access an out-of-bound area, the transaction will revert.
Note that nested arrays are extremely rare in practice. If you feel like skipping this section, feel free to.
Practice Problems
Learn more with RareSkills
See our Solidity bootcamp to learn more about smart contract development and token standards.