Eliminate duplicates in array (JSONiq)

余生长醉 提交于 2019-11-29 12:21:37
let $x := [1, 2, 4 ,3, 3, 3, 1, 2, 5]
return [ distinct-values($x[]) ]
Paul Sweatte

Use the replace function multiple times:

replace($x, "([1-5])(.*)\1", "$1")

Here's a fully functional JavaScript equivalent:

[1,2,4,3,3,1,2,5].toString().replace(/([1-5]),(\1)/g, "$1").replace(/(,[1-5])(.*)(\1)/g,"$1$2").replace(/([1-5])(.*)(,\1)/g,"$1$2")

Here is a generic JavaScript equivalent via the JSON.parse() method, which removes duplicates automatically:

var foo = [1,2,4,3,3,1,2,5];

var bar = "{" + foo.toString() + "}"

var baz = bar.replace(/(\d)(.)/g , '\u0022$01\u0022:\u0022\u0022$02')

var bop = JSON.parse(baz)

var buz = JSON.stringify(bop).replace("{","[").replace("}","]").replace(/:""/g,"")

var result = Function("return" + buz)()

Here is a test harness:

regexp:replace is definitely not the way to go for this problem.

While Matthias's solution does not work on Try Zorba, this script does:

let $x := [1, 2, 4 ,3, 3, 3, 1, 2, 5]
return [ distinct-values( jn:members($x) ) ]

It returns (try out on above link):

[ 1, 2, 3, 4, 5 ]

Script needs to be a bit more verbose for DataPower Gateways JSONiq processor. There you get pretty-printed result for free:

$ cat dv.xq 
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

declare option output:method "json";
declare option jsoniq-version "0.4.42";

[ distinct-values( jn:members(.) ) ]
$ 
$ coproc2 dv.xq <(echo '[1, 2, 4 ,3, 3, 3, 1, 2, 5]') http://dp1-l3:2226; echo

[
  1,
  2,
  4,
  3,
  5
]
$ 

Hermann.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!