How to Handle Duplicate Elements in #each Svelte Block

I've encountered an issue with the related posts component on my Svelte website. While it functions correctly, there is a problem with duplicate articles showing up in the block. For example, if two articles contain three identical tags each, those articles will appear multiple times in the related posts section of each article.

<script>
    import { getMarkdownPosts } from '$lib/utils/getPosts'

    let posts = getMarkdownPosts()

    export let currentPostTitle, currentPostTags

</script>

{#await posts}
    Loading...
{:then posts}
   Related posts
    <ul>
        {#each posts as {slug, meta: {title, tags, published}}}
            {#if published}
                {#if currentPostTitle != title}
                    {#each tags as tag}
                        <!-- {#if index === 1 } -->
                            {#if currentPostTags.includes(tag)}
                                <li><a href="/blog/{slug}"><h4>{title}</h4></a></li>
                            {/if}
                        <!-- {/if} -->
                    {/each}
                {/if}
            {/if}
        {/each}
    </ul>
{/await}

Is there a way to modify this code so that this duplication issue can be resolved?

Answer №1

After careful consideration, I decided to revise the component and now it's working perfectly.

<script>
    import { fetchPosts } from '$lib/utils/fetchData'
    import { onMount } from 'svelte'

    let posts = []
    let relatedPosts = []

    export let currentPostTitle, currentPostTags

    onMount(async () => {
      posts = await fetchPosts()
      filterRelatedPosts()
    })

    function filterRelatedPosts() {
      relatedPosts = posts.filter(post => {
        // Exclude the current post and remove duplicates based on tags
        return (
          post.meta.title !== currentPostTitle && post.meta.published &&
          currentPostTags.some(tag => post.meta.tags.includes(tag))
        )
      })
    }
  </script>

  {#if relatedPosts.length > 0}
    Related posts
    <ul>
      {#each relatedPosts as { slug, meta: { title } }}
        <li><a href="/blog/{slug}"><h4>{title}</h4></a></li>
      {/each}
    </ul>
  {:else}
    No related posts found.
  {/if}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NextJS Router delays data reloading until page receives focus

Struggling with creating an indexing page in NextJS. Attempting to retrieve the page number using the router: let router = useRouter() let page = isNaN(router.query.page) ? 1 : parseInt(router.query.page); This code is part of a React Query function withi ...

Utilizing numerous X-axis data points in highcharts

I'm working with a line graph that dips straight down, like starting at (1, 100) and dropping to (1,0). The issue I'm facing is that Highcharts (https://www.highcharts.com/) only displays information for one of the points. Is there a way to make ...

I'm having trouble with my Express server routes not being accessed. The browser is displaying an error message saying 'No Data Received ERR_EMPTY_RESPONSE

I've encountered an issue with my express server while setting up an email service. Despite troubleshooting and simplifying the code to a basic 'hello world' example, the problem persists. No routes are functioning properly – requests made ...

Tips on presenting messages to users after clicking the submit button?

I am trying to extract data from a table. I am unsure if my current code is able to retrieve the value from the table. <script> function validateForm() { var x = document.forms["assessmentForm"]["perf_rating11"].value; var y = document.f ...

Price Adjuster Tracker

Recently, I coded a small JavaScript program with the purpose of: incrementing or decrementing the quantity of an item by 1 adjusting the price of an item based on the initial price However, my excitement turned to disappointment when I encountered these ...

The child user interface component is failing to respond to keypress events within the parent component in an Angular project

I am facing a challenge in adding a keyboard shortcut to open a nested child UI Tab component through a keypress event. However, the Child nested tab can only be loaded after the Parent component is loaded first. Below is the structure of the UI tree: |-- ...

Guide to developing a custom plugin for Nuxt.js

This is the content of my rpc.js plugin file: const { createBitcoinRpc } = require('@carnesen/bitcoin-rpc') const protocol = 'http' const rpcuser = 'root' const rpcpassword = 'toor' const host = '127.0.0.1&apo ...

Leveraging NextJS to perform server side rendering by injecting parameters from a caller component

I'm currently in the process of creating an application with a storefront using nextJS. I've successfully utilized getServerSideProps when loading a new page. This particular page is quite complex, as it consists of multiple components, each req ...

An AJAX event handling function returns a null value upon invocation

Recently, I've been working on a function named 'getAuthor' which includes an AJAX event. Here's the code snippet: function getAuthor(id){ $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){ ...

Update the appearance of a webpage using a custom JavaScript function

My goal is to modify a CSS style whenever a button is clicked. In order to achieve this, I have implemented a JavaScript function that creates a new class for CSS along with several other functionalities. Here's how the JS function currently appears: ...

Adaptive Website displayed within an iframe

Currently, I have a responsive website that can be viewed here. The main objective is to embed this site into an iframe while maintaining its responsiveness. I attempted embedding my site in JSFiddle for testing purposes, which you can see here. However ...

Are you familiar with manipulating Arrays or Objects in jQuery?

In JavaScript, we can create objects with keys as strings for similar functionality to an associate array. Check out this example here. For example: ".home-title":[ ["font-size","12px"], ["line-height","16px"], ], However, if you need a ...

Learn how to effectively utilize templateURL in an express and angular project

Our project utilizes Express without any view engine. To set up static directories, we have the following: app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/view')); app.use(express.static(__dirname + ...

Having trouble removing objects in angular.js?

I have developed an API to be used with Angular.js: angular.module('api', ['ngResource']) .factory('Server', function ($resource) { return $resource('http://localhost\\:3000/api/servers/:name') ...

The Battle of node.js Modules: Comparing socket.io and express.static

The server.js file I am currently running is set up as follows: module.exports = server; var express = require('express'); var fs = require('fs'); var server = express.createServer(); var port = 58000; server.listen(port); var ...

What is the process for retrieving a value from a Django view?

Would it be feasible to call a view from a JavaScript file using Ajax and have the view only return a specific value known as "this"? However, despite attempting this, an error occurs stating that the view did not provide an HttpResponse object, but instea ...

Passing an unpredictable amount of parameters to react router in a dynamic way

Within my React application, users have the ability to create both folders and files. A folder can contain an indefinite number of subfolders within it. Here is an example structure: Folder-1 |_Folder-1-1 |_Folder-1-2 |_Folder-1-2-1 |_Folder- ...

The passing of query string parameters from JavaScript to a PHP processing script is ineffective

I am looking to dynamically populate a jQWidgets listbox control on my webpage with data retrieved from a MySQL database table once the page has finished loading and rendering. PARTIAL SOLUTION: You can find a solution here. NEW PROBLEM: I have created a ...

I'm experiencing issues with event.preventDefault() not functioning properly when used within a contenteditable div

I'm currently working with some basic Angular 7.x code that involves a contenteditable div. I'm attempting to prevent the default action when a user hits the [ENTER] key, but no matter what I do, it still moves the cursor to the next line. What a ...

AngularJS: The art of object pushing

I have a small application where I need to read data from a JSON file, display it, and allow users to add records to it. Specifically, I have an array called condition within the patient object, and I want to insert a new item into this array based on user ...