Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project_serial_num. I already have the elements sorted in descending order, which works well when using a v-for loop to render them. However, my challenge is how to selectively display only the first award notice for each project_serial_num, resulting in the data for appl_id 10372234 and 10226173 being shown. Filtering by dates is not effective because an award may have expired but still be the first one for that particular project_serial_num.

           
    [{
        "appl_id": 10372234,
        "subproject_id": null,
        "fiscal_year": 2022,
        "project_num": "5R01CA261232-02",
        "project_serial_num": "CA261232",
        "award_notice_date": "2022-03-02T12:03:00Z"
    },
    {
        "appl_id": 10226173,
        "subproject_id": null,
        "fiscal_year": 2021,
        "project_num": "5K07CA214839-05",
        "project_serial_num": "CA214839",
        "award_notice_date": "2021-08-05T12:08:00Z"
    },
    {
        "appl_id": 10253554,
        "subproject_id": null,
        "fiscal_year": 2021,
        "project_num": "1R01CA261232-01",
        "project_serial_num": "CA261232",
        "award_notice_date": "2021-03-15T12:03:00Z"
    },
    {
        "appl_id": 9989810,
        "subproject_id": null,
        "fiscal_year": 2020,
        "project_num": "5K07CA214839-04",
        "project_serial_num": "CA214839",
        "award_notice_date": "2020-07-30T12:07:00Z"

    }]

Answer №1

I found inspiration in this answer from a different thread and utilized the following code snippet:

YOUR_ARRAY.filter((value, index, self) => self.findIndex(v => v.id === value.id) === index);

This function will generate a fresh array by eliminating objects that share the same id, making it suitable for direct use with v-for, saving you the trouble of creating additional variables or computed properties.

Answer №2

To prevent duplicates, consider utilizing a computed property that utilizes a Map to store values efficiently. Prior to adding a value to the Map, ensure it does not already exist within it. Below is an example of how you can achieve this:

computed:
{
  removeDuplicates()
  {
    const uniqueItems = {};
    this.data.forEach(item =>
    {
      if (!uniqueItems[item.id])
      {
        uniqueItems[item.id] = item;
      }
    });
    return Object.values(uniqueItems); // maintain order of insertion
  }
}

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

Tips for transferring multiple files from Vue.js to PHP

<form method="POST" @submit.prevent="share" > <div id="imgs"> Select Images: <input type="file" ref="file" name="file[]" multiple ></form& ...

What is the process for showing a table based on a selected value?

I could use some help - I am working on a <select> element with 4 different options in the form of <option>. What I want to achieve is to have tables that are initially not visible, and then when an option is clicked, the corresponding table wi ...

The import 'react-router' does not include an export called 'browserHistory'. This issue is coming from the /src/App.js file

I've recently started diving into the routing section of learning react, but I'm a bit puzzled by the error message I encountered. Error: Failed to compile ./src/App.js 31:19-33 'react-router' does not contain an export named 'bro ...

Ajax request results in a 400 error code

Here is the structure of my Ajax call: function Submit() { var objectData = { email: $("#email").val(), firstName: $("#firstName").val(), lastName: $("#lastName").val(), loginMode: $("#login ...

Is it possible to verify if each input is unique using the parsley validator?

As a novice, I am struggling with a task where I have 6 School Children IDs. The teacher needs to input these IDs, and while it's not vital for him to enter all of them, he must input at least one. Furthermore, if he decides to input more than one ID, ...

Tips on allowing a rectangle to be draggable using HTML5

I have been experimenting with resizable and draggable rectangles in HTML5. I've managed to create resizable rectangles, but I am having trouble getting them to drag using mouse events. You can view my JSFiddle code at the following link: here. / ...

Prisma generate: encountering issues resolving the dependency tree with Prisma, Postgresql, and NextJS integration

Every time I execute prisma generate, the following error is displayed: Prisma schema loaded from prisma/schema.prisma npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/ema ...

Having trouble generating a dynamic ref in Vue.js

I am currently working on rendering a list with a sublist nested within it. My goal is to establish a reference to the inner list using a naming convention such as list-{id}. However, I'm encountering difficulties in achieving this desired outcome. B ...

Utilizing jQuery to place an element beside another and maintain its position

I need ElementA to be positioned next to ElementB as shown in this example. The key difference is that I want ElementA to move along with ElementB if the latter is relocated. Is there a way to keep a specific element fixed to another one? Re-calculating ...

What are the advantages of compiling our CSS and JS files in Laravel? How does it benefit us?

Just starting out with Vue and came across a video where they were compiling their assets. Got me thinking, why do we need to compile our assets? Can we use Vue and Vue-router in Laravel without asset compilation? If so, how? ...

Launch a nearby hyperlink in a separate tab

I am currently facing an issue where all the URLs in a Text get linked as Hyperlinks. However, when a user types www., the browser interprets it as a local URL and associates the link with the application's URL. Does anyone know how to open a local U ...

Warning: Attention Required for Published NPM Package Fix

After successfully publishing my first package on npm, I encountered a warning when I tried to import it in Codesandbox. There was an error converting '/node_modules/protected-react-routes-generators/src/index.js' from esmodule to commonjs: Canno ...

How can I make the first option in a dropdown menu automatically selected in a select input form?

Having an issue where the first selection in my dropdown list is showing as null even though it should be selected. Here is the code: <div class="form-group mb-6"> <label class="form-label">{{ $trans('labels.departme ...

How is it that my initial response appears correct in the first log, but then suddenly changes to a 1?

I've encountered a strange issue where the response appears correctly in the initial log, but later changes to a '1' when console.log(data); is called. The screenshot illustrates the pattern: https://i.sstatic.net/zaXcg.png If you expand ...

Step-by-step guide on populating input fields with JSON data for each row

As a beginner in Programming, I have been searching for an answer to the following problem on this site for days but haven't been able to figure it out yet. To explain briefly, there will be an input form where the user can define the number of rows ...

Tips for resizing a larger image to display only a specific portion in CSS (and incorporating JS if needed)

I need to resize an image that measures 1024x1024 and is segmented into 4 quadrants: My goal is to reduce the size of this image so that quadrant 2 is 256x256 while masking out or hiding the remaining 3 quadrants, displaying only the desired section on th ...

Discovering the significance of a function's scope

I'm a bit confused about how the answer is coming out to be 15 in this scenario. I do understand that the function scope of doSomething involves calling doSomethingElse, but my calculation isn't leading me to the same result as 15. function doSo ...

Mastering React children: A guide to correctly defining TypeScript types

I'm having trouble defining the children prop in TypeScript for a small React Component where the child is a function. class ClickOutside extends React.PureComponent<Props, {}> { render() { const { children } = this.props; return chi ...

Structure of directories in NodeJS

I'm diving into the world of web development and NodeJS, embarking on the task of streamlining our app's code and directory layout. Seeking the insights of seasoned developers, I am keen to gather opinions on the file structure pattern I am cons ...

Invoke the subscribe function within the encompassing parent function

In crafting a versatile method, I have devised the following code snippet: fetchArticle(loading: Loading): void { this.articleService.getArticleById(this.data.definition.id) .map((response: any) => response.json()) .subscribe((response: ...