Grouping of XML input with XPath 3.1 and Saxon-JS

Example input

Example XPath 3.1 code

let $comp-key := function($city) { $city/@country || ', ' || $city/@name }
return 
  for $key in cities/city!$comp-key(.)=>distinct-values()
  return
    let $group := cities/city[$key = $comp-key(.)]
    return 
      map { $key : avg($group/@pop) }

Example XPath results