2

#Inside the function the arrayList has 51 items, but the function returns a 102 items arrayList #0 to #51 are int values 0 to 51, #51 to #101 are the expected json objects?

function Get-RedditTopics () {
    
    $arrayList = New-Object -TypeName "System.Collections.ArrayList"
    $url = 'https://www.reddit.com/r/worldnews/.json'
    $pages = 2
    
    $after = ""
    for ($i = 0; $i -lt $pages; $i++) {
    
        if ($i -gt 0) {
            $url = $url + "?after=$after"
        }
    
        $result = Invoke-RestMethod $url
    
        foreach ($item in $result.data.children) {
            $arrayList.Add($item.data)
        }
    
        $after = $result.data.after
    }
    return $arrayList #51 items, ok!
}

$redditTopics = Get-RedditTopics #function returns $arrayList with 102 items
write-host "redditTopics count: $($redditTopics.Count)"
Rick
  • 57
  • 1
  • 5
  • 4
    yes, 51 + 51 = 102 (because each time you [add to an arraylist, it outputs the index](https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist.add?view=net-6.0#system-collections-arraylist-add(system-object))). `$null = $arrayList.Add($item.data)` should do it :) – Santiago Squarzon Apr 18 '22 at 21:39
  • 4
    In your case it is `ArrayList.Add()` that returns the index of the added array element. This is added as _implicit_ output of your function. See the accepted answer of the linked duplicate for details about how _implicit_ output works and what you can do to suppress it. – zett42 Apr 18 '22 at 21:40
  • 2
    @Santiago Squarzon, thank you! – Rick Apr 18 '22 at 21:46

0 Answers0