Grouping of JSON input with XPath 3.1 and Saxon-JS

Example input

Example XPath 3.1 code

let $distinct-countries := distinct-values(?cities?*?country)
return
  map:merge(
    for $country in $distinct-countries
    return
      let $group := ?cities?*[?country = $country]
      return
        map { 
          $country : map { 
            "cities" : $group?name,
            "population" : sum($group?pop) 
          }
        }
   )

Example XPath results