Display the latest distinct records in Vue.js

I've hit a roadblock in my project. @StephenThomas kindly assisted me with this issue: Vue.js only show objects with a unique property but I still need to make some adjustments.

My current task involves creating a leaderboard for a game using Firestore. There's a collection called "leaderboard" that stores all the teams' scores. Each team has a start time, and every time there's an entry made for a team, the difference in time from the start to the present is stored in a property named "diff." Furthermore, all entries are timestamped.

Every team ends up having multiple entries in the "leaderboard" collection.

The goal is to display only the most recent entry for each team. Here's a snippet of what a few entries in the "leaderboard" collection look like:


step: "1"
diff: 6270
team: "1"
timestamp: 1549117702442

step: "1"
diff: 31704
team: "2"
timestamp: 1549118713605

step: "2"
diff: 30302
team: "1"
timestamp: 1549118713605

Stephen guided me through creating a computed property to filter out duplicate entries and show only one per team. However, now I face a new challenge where it doesn't display the most recent entry. For instance, in the example above, Team #1 shows Step #1 when it should actually display the results of Step #2.

Below is the computed property:

    
computed: {
    teams() {
        return this.trackers.reduce((teams, tracker) => {
            if (teams.find(team => team.info.team_id === tracker.team.info.team_id) === undefined) {
                teams.push(tracker.team);
                teams.sort(function(a, b){
                    return a.tracker.diff-b.tracker.diff
                })
            }
            return teams;
        }, []);
    }
},

And here is the generated HTML:

<v-list-tile v-for="(team, objKey) in teams" :key="objKey" avatar>

    <v-list-tile-action >{{ objKey +1 }}</v-list-tile-action >

    <v-card-title class="text-sm-left">
       <v-list-tile-title v-text="team.info.team_name"></v-list-tile-title>
       <v-list-tile-sub-title>{{team.tracker.diff | moment}}</v-list-tile-sub-title>        
    </v-card-title>

</v-list-tile>

Any assistance on this issue would be highly appreciated!

Answer №1

I received assistance from a friend in locating the solution...

fetchTeams() {
            return this.trackers.reduce((teamList, tracker) => {
                if (teamList.find(currentTeam => currentTeam.info.team_id === tracker.team.info.team_id) === undefined) {
                    teamList.push(tracker.team);
                } else {
                    let index = teamList.findIndex(currentTeam => currentTeam.info.team_id === tracker.team.info.team_id);
                    if (tracker.team.tracker.timestamp > teamList[index].tracker.timestamp) {
                        teamList[index] = tracker.team;
                    }
                }
                teamList.sort(function(a, b){
                    return a.tracker.diff-b.tracker.diff
                })
                return teamList;
            }, []);
        }

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

Steps for iterating through an array within an object

I currently have a JavaScript object with an array included: { id: 1, title: "Looping through arrays", tags: ["array", "forEach", "map"] } When trying to loop through the object, I am using the following ...

Enhance Shipping Options on Your Woocommerce Cart

I am facing a challenge with providing delivery options for three different countries in my e-commerce store. I want the customer to be able to select their country and instantly see the available delivery methods without having to refresh the entire page ...

Exploring the power of searching JSON data using ReactJS

After reading through the "Thinking in React" blog, I'm inspired to create something similar. Instead of filtering an array table, I want it to display the row that matches the input value. I have attempted this and created a jsfiddle example here: j ...

AngularJS document object model selector

My custom directives use jQuery for animation effects because I find angular's built-in ngShow/ngHide to be functional but not visually appealing. I vaguely remember reading in the documentation that Angular has its own DOM selector, something like an ...

Is there a more efficient approach to streamline Javascript code similar to the chaining method used in JQuery?

When working with jQuery, it's possible to streamline the code by running multiple methods in a single statement: $("#p1").css("color", "red").html("Hello world!").attr("class","democlass"); But how can this be accomplished in Javascript? document. ...

When accessing req.user in code not within a router's get or post method

Is there a way for me to access the data in the User schema outside of a post or get request? I am asking this because I would like to use this information elsewhere. The user schema is defined as follows: const mongoose = require('mongoose'); c ...

Pattern for Ajax callback in Javascript

I'm facing an issue with the code snippet below. var bar = { ajaxcall : function(){ var _obj = {}; $.ajax({ headers: { 'Content-Type': "application/json; charset=utf-8", 'da ...

Exploring the method of implementing a "template" with Vue 3 HeadlessUI TransitionRoot

I'm currently working on setting up a slot machine-style animation using Vue 3, TailwindCSS, and HeadlessUI. At the moment, I have a simple green square that slides in from the top and out from the bottom based on cycles within a for-loop triggered by ...

Coordinating Angular to communicate with Node.js to send and receive data

I am currently working on a project using express.js, but I would like to integrate angular into the project to create a single page application. The website currently refreshes the entire content from the server whenever a link is clicked, which seems ine ...

Switch between display modes by clicking using collections

I am trying to figure out how to create a function that will only show content for the specific element in which my button is located. Currently, when I click the button it shows content for all elements with the 'one' class, but I want it to dis ...

Is there a way to prevent this JavaScript code from deleting the initial row of my table?

Looking at the code provided, it's evident that creating and deleting new rows is a straightforward process. However, there seems to be an issue where the default/origin/first row (A-T) gets deleted along with the rest of the rows. The main requiremen ...

Implementing proper data return in MVC4 through an Ajax call

When using ajax to call an action in a controller, the code may result like this: $.ajax({ type: "POST", url: "getUserInfo.json", data: "", success: function (data) { if (data.resultInfo.resu ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

Utilize Webpack to import a file containing exclusively global constants

I have a specific file filled with essential global constants that I am attempting to bring into another JavaScript file. This way, I can utilize these constants within the code of the second file. globalConstant.js global.RoutesOffersPage = { routes: ...

Assistance needed with WebSocket and Node.js: Unable to connect to wss://domain:8080 - Issue is not specific to any browser

Greetings, this is my initial inquiry on stack overflow so I'll give it my best shot. Despite going through numerous related questions, I haven't found the solution to my issue. I recently delved into Node.js because I required websockets for ce ...

The MongoDB operator "$in" does not recognize the type array that currently exists in the field

When attempting to execute an aggregate query in mongodb, I encountered an issue with the "$in" operator stating that the field passed is not recognized as an array. Here is the aggregate query being used: [ { '$match': { 'isVis ...

Tips on manually refreshing AngularJS view using ControllerAs syntax?

As I work on creating a user-friendly dashboard with widgets that can be sorted, docked, and floated, I encountered an issue. The controls I am using generate floating widgets as HTML at the bottom of the DOM, outside the controller scope where they were c ...

What is the best way to implement bypassSecurityTrustResourceUrl for all elements within an array?

My challenge is dealing with an array of Google Map Embed API URLs. As I iterate over each item, I need to bind them to the source of an iFrame. I have a solution in mind: constructor(private sanitizer: DomSanitizationService) { this.url = sanitizer. ...

Why is the Vuetify slider stuck in the center and not budging?

The slider remains static in the center without any movement. https://i.stack.imgur.com/7it9R.png Version Information Vue 3.2.45 Vuetify 3.1.0 Vite 4.0.0 <script> export default { data: () => ({ slider1: 0, slider2: 50, slider3: ...

Issue with rendering an object's property using EJS

Trying to include the author's username in reviews within an ejs template for my app. The following code snippet: <%= review.author %> is functioning correctly and displays: { _id: 5eff6793e7f26811e848ceb1, username: 'mike', __v: 0 ...