Removing duplicate loops within a table in a Vue component

I am facing an issue with duplicate json data and need help removing the duplicates based on the id_cms_users. How can I display the cleaned data in a table?

I found a method on https://codepen.io/roverv/pen/YQvdya but it only displays data from one column.

<tr  v-for="coba in ayam ">
  <td>{{ coba.id_cms_users }}</td>
  <td>{{ coba.cms_users_name }}</td>
  <td>{{ coba.berminat }}</td>
</tr>

var app = new Vue({
  el: "#app",
  data: function () {
    return {
      ayam: [{
            id: 62,
            id_cms_users: 7,
            cms_users_name: "Imam Prasetyo",
            berminat: 1
        },
        {
            id: 61,
            id_cms_users: 7,
            cms_users_name: "Imam Prasetyo",
            berminat: 1
        },

        {
            id: 56,
            id_cms_users: 20,
            cms_users_name: "Nanda Rusfikri",
            berminat: 2
        }
        ]
    };
  },

});

Answer №1

To filter the array, you can use the Array#filter method along with a computed property:

var app = new Vue({
  el: "#app",
  data: function() {
    return {
      ayam: [{
          id: 62,
          id_cms_users: 7,
          cms_users_name: "Imam Prasetyo",
          berminat: 1
        },
        {
          id: 61,
          id_cms_users: 7,
          cms_users_name: "Imam Prasetyo",
          berminat: 1
        },

        {
          id: 56,
          id_cms_users: 20,
          cms_users_name: "Nanda Rusfikri",
          berminat: 2
        }
      ]
    };
  },

  computed: {
    uniqueAyam: function () {
      var existingIds = {};
      return this.ayam.filter(function (user) {
        if (existingIds[user.id_cms_users]) return false;
        return existingIds[user.id_cms_users] = true;
      })
    }
  }
});
body{background:linear-gradient(135deg,#42e695 0,#3bb2b8 100%);font-family:futura,helvetica;background-repeat:no-repeat;height:100vh;display:flex;justify-content:center;padding:2px}table{background:#FAFAFA;padding:20px;border-radius:5px;box-shadow:0 20px 50px -10px rgba(0,0,0,.2)}tr{padding:5px;box-shadow:0 1px 0 #d3d3d3;height:2rem}h1{color:#fff;text-shadow:0 2px 5px rgba(0,0,0,.2)}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8deddcde89a869d86999f">[email protected]</a>/dist/vue.js"></script>

<div id="app">

  <h1>Users</h1>
  <table>
  
    <!-- Replace `ayam` with `uniqueAyam` -->
    
    <tr v-for="coba in uniqueAyam">
      <td>{{ coba.id_cms_users }}</td>
      <td>{{ coba.cms_users_name }}</td>
      <td>{{ coba.berminat }}</td>
    </tr>
    
  </table>


</div>

Answer №2

Utilize a reduce function to check if the item is already in the results array; if not, add it, otherwise return the current results.

const data = [
  {
    id: 62,
    id_cms_users: 7,
    cms_users_name: 'Imam Prasetyo',
    berminat: 1
  },
  {
    id: 61,
    id_cms_users: 7,
    cms_users_name: 'Imam Prasetyo',
    berminat: 1
  },

  {
    id: 56,
    id_cms_users: 20,
    cms_users_name: 'Nanda Rusfikri',
    berminat: 2
  }
];

const uniqueUser = array =>
  array.reduce(
    (results, item) => (results.find(i => i.id_cms_users === item.id_cms_users) ? results : [...results, item]),
    []
  );

console.log(uniqueUser(data));

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

What is the best way to implement an automatic logout feature in asp.net that will log out my site after 10 minutes of inactivity?

Looking for a solution to automatically log out a site in asp.net when it is idle? Here's what you can do: Set the session timeout to 10 minutes in the web.config file under authentication. For instance, if the site has been idle for 9 minutes, you ca ...

Ways to update the number of rows displayed per page

I'm looking to modify the select options on this page. Is there a way to customize them? https://i.sstatic.net/w02yn.png I'm not sure if there are any props available for that. Any suggestions on how to accomplish this? ...

What is the best way to retrieve the value stored in a variable?

In my Node.js program, I have a snippet of code where I am working with a map named `transMap`. My goal is to retrieve the value for 'yy', which should be "ipaddress", and then output it as JSON. While I expected the JSON response to be { "ipaddr ...

Encountered SyntaxError: An unexpected token has been found while integrating leaflet with flask

Despite adding all necessary scripts and configuring my API_KEY in config.js, I keep getting an error message saying "Uncaught SyntaxError: Unexpected token." I have double-checked my API key multiple times, and it seems to be correct. Here is a snippet f ...

Receiving an unspecified reply after making an ajax request

I am experiencing difficulties with retrieving the results from an ajax call. When I use console.log(data) to log the data, it is showing [undefined]. Here is the code snippet for the ajax call: $.get(root+'hotels/functions/ean/get-zones.php', { ...

Collection of clickable images that lead to creatively designed individual pages

Being relatively new to JavaScript and jQuery, my knowledge is solid when it comes to HTML & CSS. Currently, I have a page with 20 minimized pictures (with plans to increase to 500+ images) that open into a new page when clicked. Although I have no issues ...

Using an array as a route parameter triggers a "Expected to not repeat" warning

Every time I attempt to set up a router-link with an array as the parameter, the link functions properly but triggers the following warning : "Missing param for named route "start-run": Expected "files" to not repeat, but received ["aaa"] router.js .. ...

Validation works correctly during keyup events, but is ineffective during keypress events

When using the input box, there are certain validations in place: 1) The length input box should accept up to 3 integer values (no decimals). 2) The height input box should accept 3 integer numbers and decimals up to 2 places. Initially, everything works ...

Streamlining a complex task in JavaScript

I am currently exploring options to streamline my code so that I don't need to repeat the same function 38 times. Instead, I would like to have a single function that can handle 38 different IDs separately. The script is designed to randomly select a ...

Creating a custom button in a Material UI table using React

I am looking for a solution specific to customizing the MaterialTable Actions column by adding an icon for viewing details. Although I have reviewed the documentation and API, I have not found an efficient way to achieve this customization. My project inv ...

In the frontend, I seem to have trouble accessing elements of an array using bracket notation, yet strangely it works flawlessly in the backend

I am encountering a peculiar issue as a newcomer to coding. I have an array retrieved from the backend database, and my goal is to access individual elements of this array in the frontend using bracket notation. While I can successfully access the elements ...

What is causing the while loop in Mongodb to repetitively insert the same document rather than cycling through the documents?

Currently, I am in the process of redesigning a MongoDB database structure where the reviews for a specific product will be integrated into the product document itself, rather than maintaining separate collections for products and reviews. I have created a ...

My goal is to create a React js application that can automatically generate unique card designs

I've been working on developing cards using react js that are automatically generated based on API data. However, all the cards currently display one below the other and I'm aiming to have them designed in a row fashion. I've tried various m ...

What is the best way to tidy up a function within a useEffect hook?

When updating state within a useEffect hook while using async/await syntax, I encountered an error regarding the cleanup function. I'm unsure how to properly utilize the cleanup function in this scenario. Error: Warning - A React state update was att ...

What is the best way to transfer a JavaScript object to a VueJS component?

Even though it may seem like a basic question, I'm having trouble figuring out how to accomplish this in VueJS Here's the code I have in HTML: <script> var config = {'cols':4,'color':'red'} </script> ...

Connecting a JavaScript variable

Is it possible to include a JavaScript variable in a link? I've tried the code below but it just shows a blank page. The viewData.php file will contain PHP GET Variables used to retrieve data based on the period and type, which determine whether renta ...

How can you adjust the level of granularity for re-rendering components in Vue?

Currently, I am using a component to display a dynamic table with numerous rows. Whenever new rows are added or existing ones are modified, Vue ends up re-rendering the entire table, leading to a significant delay that I hope to avoid. While I have implem ...

Conceal a component using v-if when there is a change in the state

I've been racking my brain for the past couple of days trying to wrap my head around reactivity, but it's just not clicking for me yet. Here's the component in question: <template> <div class="tile-content"> <router-li ...

Exploring the world of cookie security with SameSite and Secure features in ExpressJS

Despite having the specified settings on my express application, a warning keeps appearing in the console. Has anyone encountered this error before? I found some information related to it here: https://github.com/expressjs/express/issues/3095 The version ...

Passing a variable from index.html to a script in Angular

I am attempting to pass the array variable 'series' to the script in HTML. Is there a way to do this? app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app ...