Search code examples
arangodbaql

Arangodb array reduce


Given the following:

LET replacements = [
  ["foo", "bar"],
  ["bar", "baz"]
]

LET title = "foo"

// JS CODE
// title = replacements.reduce((acc, r) => r.replace(acc[0], acc[1]), title);
// or
// for (const r of replacements) {
//   title = title.replace(r[0], r[1]);
// }

RETURN title

How is the logic I described with JS possible to implement in aql?

I can't seem to get FOR loops to work without returning something, and LET itself seems not to allow further reassignment.


Solution

  • This could be a case for a user function.

    In arangosh:

    127.0.0.1:8529@_system> require("@arangodb/aql/functions").register(
        "MYFUNC::REPLACEEQ", 
        function (replacements, title) {
            return replacements.reduce(
                    (t, r) => t.replace(r[0], r[1]),
                    title
            );
        }
    );
    

    The AQL-Query:

    LET replacements = [
      ["foo", "bar"],
      ["bar", "baz"]
    ]
    
    RETURN MYFUNC::REPLACEEQ(replacements, "foo")
    // => ["baz"]