Vue js: Stop Sorting array items; only display the resulting array

I recently came across a tutorial on voting for a Mayoral Candidate. The tutorial includes a sort function that determines the winner based on votes. However, I noticed that the sort function also rearranges the candidate list in real time, which is not ideal as it causes the Candidate Name and Vote buttons to shift their positions. My preference is to have the sort function only affect the result and not alter the layout of the page.

HTML

<div class="container">

  <div id="mayor-vote">
    <h2>Mayor Vote</h2>
    <ul class="list-group" style="width: 400px;">
      <li v-for="candidate in candidates" class="list-group-item clearfix">
        <div class="pull-left">
          <strong style="display: inline-block; width: 100px;">{{ candidate.name }}:</strong> {{ candidate.votes }}
        </div>
        <button class="btn btn-sm btn-primary pull-right" @click="candidate.votes++">Vote</button>
      </li>
    </ul>
    <h2>Our Mayor is <span class="the-winner" :class="textClass">{{ mayor.name }}</span></h2>
    <button @click="clear" class="btn btn-default">Reset Votes</button>
    <br><br>
    <pre>
      {{ $data }}
    </pre>
  </div>

</div>

JS - refer to computed property

 new Vue({

  el: '#mayor-vote',

  data: {
    candidates: [
      { name: "Mr. Black", votes: 140 },
      { name: "Mr. Red", votes: 135 },
      { name: "Mr. Pink", votes: 145 },
      { name: "Mr. Brown", votes: 140 }
    ]
  },

  computed: {
    mayor: function(){
      var candidateSorted = this.candidates.sort(function(a,b){
        return b.votes - a.votes;
      });
      return candidateSorted[0];
    },
    textClass: function() {
      return this.mayor.name.replace(/ /g,'').replace('Mr.','').toLowerCase();
    }
  },

  methods: {
    clear: function() {
      this.candidates = this.candidates.map( function(candidate){
        candidate.votes = 0;
        return candidate;
      })
    }
  }
});

Feel free to check out the working version here: https://jsfiddle.net/7dadjbzs/

Answer №1

If your goal is to identify the mayor, meaning the candidate with the highest number of votes, there's no need to sort the array. You can simply locate the candidate with the maximum votes and return it without making any changes to the original array. Here's how you can achieve this:

  computed: {
    mayor: function(){
      return this.candidates.slice(0).sort(
 function(a, b) { return b.votes - a.votes })[0]
    },

Check out the latest example.

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 sending additional parameters to an MVC controller without including them in the URL when using the JavaScript window.open method

<a href="#" onclick="openAnchor('<%# DataBinder.Eval(Container.DataItem,"Url") %>', '<%# DataBinder.Eval(Container.DataItem,"infoToSend") %>')"> </a> openAnchor= function (Url, infoToSend) { window.open(Url, ...

Resetting the store variable in Vuex when changing routes

I am currently working on a method to navigate back to the previous route and reset a variable stored in vuex. Here is what I have attempted so far: (In the component's template): <button type="button" class="btn btn-primary btn-lg btn-block" @cl ...

Looping through an array and adding its elements to a dictionary using JavaScript

I am struggling to figure out how to iterate over a dictionary with values in the form of arrays and then organize those values into a new dictionary. I am unsure of the steps needed to achieve this. Below is the data I need to iterate through: { t: [&quo ...

Fetching client-side data in a Functional Component using Next JS: The proper approach

I have a functional component that includes a form with existing data that needs to be populated and updated by the user. Within this component, I am using a custom hook for form handling. Here is an example: const [about, aboutInput] = useInput({ t ...

Error: The global variable cannot be emptied due to an issue with the Ajax request

As someone who is relatively new to the world of Javascript/jquery and async, I have spent a significant amount of time reading through various forums. Unfortunately, I have yet to come across a solution that addresses my specific issue. The problem at ha ...

Using Jquery Regex to Validate Numeric Range Input on KeyUp Event in an Input Field

I have been spending quite a few hours attempting to figure out a solution for this issue, but unfortunately, I haven't had much success. My goal is to add a Keyup/KeyPress event that only allows values between 2 and 1827. I am using an aspx inputbox ...

The authentication for npm failed with a 401 error code when attempting to log in

When attempting to sign in to npm using the command npm login and providing my username, password, and email, I am encountering the following error message: The Registry is returning a 401 status code for the PUT request. Even though I have used the sa ...

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

How can I use Ajax code to send data to a PHP page and receive the results as a JSON-encoded multidimensional array containing information on each item?

Apologies for the unconventional question title. What I am trying to accomplish is managing two tables in my database: a hotel table (table1) and a room type table (table2). My goal is to allow customers to customize their travel packages by changing hote ...

Tips for circumventing the use of responsive tables in Buefy

I am facing a challenge with displaying data in a Buefy table in a way that it appears as a conventional table with columns arranged horizontally on all devices, rather than the stacked cards layout on mobile. In order to accommodate the content appropriat ...

Employing ngModel within an (click) event in Angular 4

I have this html code snippet: <div class="workflow-row"> <input type="checkbox" id="new-workflow" [(ngModel)]="new_checkbox"> <label>New Workflow</label> <input type="text" *ngIf="new_checkbox" placeholder="Enter ...

What strategies can I implement to minimize repetition in React when utilizing the useState hook?

I have implemented useState in my React Native application. I defined states named lstandtime and lacttime. Additionally, I have created functions called onSubmitfunc, LsonChangefunc, and LaconChangefunc. We initially required 3 instances of the MainCons ...

PM2 continuously restarting KeystoneJS application in a loop

My keystonejs application is successfully clustered using throng, but I am encountering an issue when running the following code: const throng = require("throng"), dotenv = require('dotenv'); (function usedotenv() { try { dote ...

Fading away backdrop images for the header

I've created a header class in my CSS with the following styling- header { background-image: url('../img/header-bg.jpg'); background-repeat: none; background-attachment: scroll; background-position: center center; .backg ...

How can we eliminate all elements from jQuery except for the first and second elements?

HTML <div class="geo_select"> <h3>header 3</h3> in Above HTML code i want to remove all element except <h3> and default content<div> inside the <div class='geo_select'> in jquery.. How to remove all ...

Implement handleTextChange into React Native Elements custom search bar component

I need help with passing the handleTextChange function in the SearchBarCustom component. When I try to remove onChangeText={setValue} and add onchange={handleTextChange}, I am unable to type anything in the search bar. How can I successfully pass in the ...

AngularJS: The blend of bo-bind, bindonce, and the translate filter

I am currently working with angular 1.2.25, angular-translate 2.0.1, angular-translate-loader-static-files 2.0.0, and angular-bindonce 0.3.1. My goal is to translate a static key using bindonce. Here is the code snippet I have: <div bindonce> < ...

Dealing with the percentage sign in table names during data retrieval

When using React and Express to retrieve and store data in JSON format, what is the correct way to reference tables that have a percentage sign in their name? componentDidMount() { // Retrieve data from http://localhost:5000/citystats, sort by ID, t ...

The value assigned to a dynamically created array in a void function may not be the same when returned in the main() function

Having a bit of trouble with dynamic arrays in my C program. Everything was running smoothly until I was required to move the creation of the dynamic array into a separate void function. After doing so, the program continued to work fine until I needed to ...

The domain retrieval is contingent on the language preference of the user

A task has been assigned to create a script in JavaScript/jQuery (or other suitable technologies) that will return a domain with a .pl extension if the user's browser language is set to Polish. Otherwise, the script should return a .eu domain extensio ...