6

I'm trying to remove duplicates in the array. I have tags from posts, which is also array:

tags: ['react', 'javascript', 'node']

and from map function I have output like this: node react javascript react javascript react javascript node

<div class="tags">
  {posts.map(post =>
    post.frontmatter.tags.map(tag => (
      <Link
        key={tag + `tag`}
        to={`/tags/${kebabCase(tag)}/`}
        className="tag is light"
      >
        {tag}
      </Link>
    ))
  )}
</div>

I've tried to implement .filter and reduce, but I'm stuck.

Thanks in advance

BloodOverdrive
  • 301
  • 1
  • 3
  • 15
  • Forget the fancy filter and map methods and break the problem down. You need to iterate over the array and check if each item has been encountered before. You can accomplish this with an object literal (i.e. a dictionary, same thing in this case). Though you probably won't, I'd encourage you to try and figure this out based on what I'm writing. It'll help you out in the long run. – Geuis Dec 30 '20 at 20:05

3 Answers3

9

You can use a Set to obtain the unique elements from the array and use spread syntax to get the result as an array.

const arr = ["node", "react", "javascript", "react", "javascript", "react", "javascript", "node"];
const res = [...new Set(arr)];
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
3
var sandwiches = ['turkey', 'ham', 'turkey', 'tuna', 'pb&j', 'ham', 'turkey', 'tuna'];
var deduped = Array.from(new Set(sandwiches));

// Logs ["turkey", "ham", "tuna", "pb&j"]
console.log(deduped);
1

Put the values in a Set will omit duplicates and put it back in a new array to map over it.

<div class="tags">
  {posts.map(post =>
    [...new Set(post.frontmatter.tags)].map(tag => (
      <Link
        key={tag + `tag`}
        to={`/tags/${kebabCase(tag)}/`}
        className="tag is light"
      >
        {tag}
      </Link>
    ))
  )}
</div>
Michiel
  • 344
  • 2
  • 9