Using Vue.js to eliminate duplicate values from a filtered array of objects

How can I eliminate duplicate data from a v-for loop in Vue.js? I have an array of clients and another array of categories. When filtering the categories based on clientIDs, I noticed that there are duplicates present.

Please choose a client from the options below.

var app = new Vue({
  el: "#app",
  data() {
    return {
      clientId: 0,
      clients: [{
          "id": 1,
          "clientName": "Rafael Ellison"
        },
        {
          "id": 2,
          "clientName": "Tad Beasley"
        },
        
      ],
      categories: [{
          "clientId": 1,
          "purchaseType": "Purchase Type  1"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type  1"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type 2"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type 2"
        },
        {
          "clientId": 2,
          "purchaseType": "Purchase Type 2"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type 3"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type 3"
        },
        {
          "clientId": 2,
          "purchaseType": "Purchase Type 3"
        },
        {
          "clientId": 1,
          "purchaseType": "In veritatis anim al"
        }
      ],
    }
  },
  computed: {
    filteredPurchase() {
      return this.categories.filter(
        (client) => client.clientId == this.clientId
      );
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <div>
    <div>
      <label>Under Client</label>
      <select v-model="clientId">
        <option value="" selected>select clients</option>
        <option v-for="client in clients" :key="client.id" :value="client.id">{{client.clientName}}</option>
      </select>

    </div>

    <div>
      <label for="purchaseCategoryId">Purchase Type</label>
      <div class="input-group">
        <select multiple>
          <option value="" selected>select purchase Type</option>
          <option v-for="purchase in filteredPurchase" :key="purchase.id" :value="purchase.purchaseType">{{purchase.purchaseType}}</option>
        </select>
      </div>
    </div>
  </div>

</div>

There are multiple purchase types with identical names but different clientIDs. How can I remove these duplicate values from the list of purchase types?

Answer №1

You can eliminate duplicates by creating a computed property:

var app = new Vue({
  el: "#app",
  data() {
    return {
      clientId: 0,
      clients: [{"id": 1, "clientName": "Rafael Ellison"},
        {"id": 2, "clientName": "Tad Beasley"}, 
      ],
      categories: [{"clientId": 1, "purchaseType": "Purchase Type  1"},
        {"clientId": 1, "purchaseType": "Purchase Type  1"},
        {"clientId": 1, "purchaseType": "Purchase Type 2"},
        {"clientId": 1, "purchaseType": "Purchase Type 2"},
        {"clientId": 2, "purchaseType": "Purchase Type 2"},
        {"clientId": 1, "purchaseType": "Purchase Type 3"},
        {"clientId": 1, "purchaseType": "Purchase Type 3"},
        {"clientId": 2, "purchaseType": "Purchase Type 3"},
        {"clientId": 1, "purchaseType": "In veritatis anim al"}
      ],
    }
  },
  computed: {
    uniqueItems() {
      return [...new Map(this.categories.map(v => [JSON.stringify(v), v])).values()]
    },
    filteredPurchases() {
      return this.uniqueItems.filter(
        (client) => client.clientId == this.clientId
      );
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <div>
    <div>
      <label>Select Client</label>
      <select v-model="clientId">
        <option value="" selected>Choose a client</option>
        <option v-for="client in clients" :key="client.id" :value="client.id">{{client.clientName}}</option>
      </select>

    </div>

    <div>
      <label for="purchaseCategoryId">Select Purchase Type</label>
      <div class="input-group">
        <select multiple>
          <option value="" selected>Choose purchase type</option>
          <option v-for="purchase in filteredPurchases" :key="purchase.id" :value="purchase.purchaseType">{{purchase.purchaseType}}</option>
        </select>
      </div>
    </div>
  </div>

</div>

Answer №2

This issue is mainly related to JavaScript.

You can utilize the Set constructor to create sets, which are collections of unique items.

To address this problem, I took the following steps-

  1. I utilized the Set operator along with JSON.stringify to form a set of stringified objects.
  2. I converted the set back to an array using the spread(...) operator.
  3. Finally, I changed the array of strings into an array of objects using JSON.parse.

The duplicate entries in the purchaseTypes with the same clientId have been removed. You can view the demo below-

var app = new Vue({
  el: "#app",
  data() {
    return {
      clientId: 0,
      clients: [{
          "id": 1,
          "clientName": "Rafael Ellison"
        },
        {
          "id": 2,
          "clientName": "Tad Beasley"
        },

      ],
      categories: [{
          "clientId": 1,
          "purchaseType": "Purchase Type  1"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type  1"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type 2"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type 2"
        },
        {
          "clientId": 2,
          "purchaseType": "Purchase Type 2"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type 3"
        },
        {
          "clientId": 1,
          "purchaseType": "Purchase Type 3"
        },
        {
          "clientId": 2,
          "purchaseType": "Purchase Type 3"
        },
        {
          "clientId": 1,
          "purchaseType": "In veritatis anim al"
        }
      ],
    }
  },

  computed: {
    filteredPurchase() {
      let categories = this.categories.filter(
        (client) => client.clientId == this.clientId
      );
      return [...new Set(categories.map(a => JSON.stringify(a)))].map(a => JSON.parse(a))
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <div>
    <div>
      <label>Under Client</label>
      <select v-model="clientId">
        <option value="" selected>select clients</option>
        <option v-for="client in clients" :key="client.id" :value="client.id">{{client.clientName}}</option>
      </select>

    </div>

    <div>
      <label for="purchaseCategoryId">Purchase Type</label>
      <div class="input-group">
        <select multiple>
          <option value="" selected>select purchase Type</option>
          <option v-for="purchase in filteredPurchase" :key="purchase.id" :value="purchase.purchaseType">{{purchase.purchaseType}}</option>
        </select>
      </div>
    </div>
  </div>

</div>

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

Trick to enable editing in Bootstrap Select Combobox

Is there a way for users to add their own options to bootstrap-select? Greetings! I have spent some time searching for a straightforward solution that is compatible with Bootstrap 4 styling. Despite exploring various suggestions, as well as unresolved thr ...

What could be causing the issue with my dependency injection in my Angular application?

Let's get started angular.module('app', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) This is my simple factory. Nothing fancy here angular.module('app') .factory(&apos ...

Error message: The variable datepicker_instActive is not defined within Jquery-ui Datepicker

Having trouble with a Rails + Angular app where I've implemented the jquery-ui datepicker. The console is showing an error that says: TypeError: datepicker_instActive is undefined if(!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? ...

Using a Function to Retrieve Styles in React Native for Android

My goal is to dynamically add views based on the data received from JSON. Each event should be represented with a different color: red or blue. The app will insert a view accordingly. class MainPage2 extends Component { constructor () { super() var s ...

Vue looping through nested checkbox groups

Here is an object I am working with: rightGroups: [ { name: "Admin Rights", id: 1, rights: [ { caption: 'Manage Rights', name: 'reports', ...

The Axios Catch function is triggered unexpectedly despite receiving a 200 (Successful) response

Currently, I am encountering a perplexing issue with my Electron Vue App that utilizes Axios for HTTP calls to my Laravel Server. While everything functioned flawlessly in the Dev mode of Electron, chaos ensued once I built the app into an install and depl ...

Enhancing JavaScript Asynchronous Programming with EventLoop and async/await

Exploring the intricacies of how JavaScript processes asynchronous methods led me to dive into async/await. In an effort to gain a complete understanding, I crafted the following example: async function first() { console.log(9); await Promise.resolv ...

Do not reload the page after a successful ajax request

I'm using an Ajax section to submit data in Laravel. I want the page to not reload if the submission is successful, but to reload if there's an error. Currently, when there is an error, the page reloads correctly. However, I'm facing an issu ...

Dynamically Remove One Form from a Django Formset

I have been using the following code to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> ...

Unable to locate the React Native variable named "NetworkStatus"

I have been working on implementing a code to test internet connectivity using react native NetInfo from '@react-native-community/netinfo'. Unfortunately, I keep running into an error that says "Can't find variable: connectionStatus&quo ...

Update the content of an image in a Div without altering its filename

My application's backend updates an image file and sends the filename back to the front-end: $('#giffinal').html(ResponseGo); However, when I update the image again through the backend, the code in the div on the front-end does not change. ...

What could be preventing me from successfully calling the JavaScript AJAX function in this particular situation?

Here is my code snippet from a smarty template: <form name="transaction_form" id="transaction_form"> <table class="trnsction_details" width="100%" cellpadding="5" > <tbody> <tr> ...

Using the OR operator in an Angular filter

How can I create a filter with a range slider that shows multiple categories when it's in a certain position? I have tried using the code below to filter based on the range, but it only captures the first word after the OR operator. Can anyone provid ...

AngularJS: The power of dynamic HTTP POST parameter names

Utilizing an API to update profile information allows for the addition of a nickname, email, phone number, or password in the request parameters, which will then be updated in the database. When updating a specific field, such as Nickname: { "nickname": ...

Use Angular and JavaScript to fetch HTML from a mySQL database and dynamically render it on a webpage

I'm currently utilizing Angular for the front end and Node for the back end. The data is retrieved from a MySql database where it's manually stored in text format with HTML tags. For example: <ul> <li>item1</li> <li> ...

Managing user input in Node.js

Users are required to input a URL in the form (e.g: "") and I need to be able to access and read the content from that URL. I am uncertain about my current method. What should I enter in the URL field below? var options = { url: '....', ...

Troubleshooting: JQuery dropdown selection not updating image display

I am trying to create a select menu that changes the car image when a user selects a different model, but for some reason it is not working. Here is what I have tried: <h2 class="model">A6 <img src="images/3.jpg" id="image" width="544" height="2 ...

The error message "TypeError: Unable to access the 'get' property of an undefined vue js object" appeared

Struggling to grasp the concept of vue.js, I am currently navigating my way through understanding how to fetch or call an API. Setting up my index.html and app.js, along with the required packages in the node_modules, has been relatively smooth. However, ...

Refreshing certain sections of a webpage without the need to refresh the entire page

If you want to understand better, it would be helpful if you could check out my website first at: The main part of the website is a stream from Own3D.tv displayed through an iframe (line 342). My objective is to have the ability to click on a specific str ...

Is React the best solution for managing a lengthy list that requires constant data updates?

In order to display a long list with over 2000 entries that changes dynamically, I am utilizing react redux. Each second, at least one new row is added to the list data. My current approach involves mapping through the list data in the render method like t ...