'return nested array solidity

Is it possible to return an array in solidity?

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;

contract Test {
    constructor() {}
    function multiArray() external pure returns (uint256[2][] memory doubleArray) {
        doubleArray[0] = [uint(12345678),uint(1234567)];
      return doubleArray;
    }
}

this does not work, but I thought with solidity > 0.8.0 it should be possible, also with "ABIEncoderV2"?



Solution 1:[1]

Nested arrays are still incomplete but they work at a certain level. Currently, nested arrays can only be used within an internal call to functions that are either private or internal. They should also be stored in storage or memory.

The biggest issue is using them in the calldata as a parameter or return statement which is not yet supported.

I'll recommend trying to find another way to return the nested array information like a mapping, struct, or even returning multiple lists and then working with them inside the function.

Another alternative is to pass the data as bytes and extract the array data or vice-versa. However, this can have a high gas cost on large arrays and some other problems. To use this method you can take advantage of the new ABI encoder.

Solution 2:[2]

Solidity support 1D array only. Multidimensional arrays are yet to come.

// SPDX-License-Identifier: GPL-3.0;
pragma  solidity >=0.7.0 <0.9.0;
contract Test{
    string[] A=["A","B"];
    function fun() public view  returns(string[] memory){
        return A;
}
}

enter image description here

Solution 3:[3]

Try to initialize the array first and then return values by index. You can also use a mapping, but keep in mind you can't easily iterate over it.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract NestedArrays{
    
    mapping(uint256 => uint256[]) mappingArray;
    uint256[2][] multiArray;

    constructor(){
        multiArray.push([1,2]);
        multiArray.push([3,4]);

        mappingArray[0] = [10,20];
        mappingArray[1] = [30,40];
    }

    function getMultiArray() public view returns(uint256[2][] memory){
        return multiArray;
    }

    function getMultiArrayMember(uint256 index) public view returns(uint256[2] memory){
        require(multiArray.length > index, "wrong index");
        return multiArray[index];
    }

    function getMappingArrayMember(uint256 index) public view returns(uint256[] memory){
        return mappingArray[index];
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mijail Piekarz
Solution 2 aakash4dev
Solution 3 DOBBYLABS