Unique filter in Nunjuck

Asked by At


systems:
- name: Fred
  country: DE
- name: Wilma
  country: US
- name: Pebbles
  country: DE
- name: Dino
  country: US

---

# Systems 

Countries: {{ page.systems | join(",", "country") }}

I am trying to create a GitBook page with a list of items containing no duplicates. I.e I would want to apply a 'unique' filter or 'distinct' filter in my Nunjucks template for the page. The template needs to process the page variables (YAML). The above template generates the output:

Countries: DE,US,DE,US

I would like it to produce the output

Countries: DE,US

How could I achive that? (Given that 'unique' filter is not supported with Nunjucks.)

1 Answers

0
Aikon Mogwai On

You can extend your Nunjucks through Custom filter

const nunjucks = require('nunjucks');
const env = new nunjucks.Environment(/* loaders etc... */);
env.addFilter('unique', arr => arr instanceof Array && arr.filter((e, i, arr) => arr.indexOf(e) == i) || arr);

let out = env.renderString(`{{[1, 2, 3, 2] | unique }}`);
console.log(out);