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

Connecting an image to the Laravel Public folder using Laravel and Vuejs

In the past, I utilized the following code when using blade: <img src="{{ asset('images/3379.svg') }}" alt="computer"> However, now that I have switched to Vue, this code no longer functions. Can anyone provide guidanc ...

Only initiate the loading of the iframe within the div upon clicking a specific element

Is there a way to delay loading the content of a div until it's clicked, instead of having all data loaded at once when the page loads? I noticed that removing unnecessary divs made the page load much faster. How can I prevent all data from being loa ...

Reorganizing objects upon insertion in Mongo DB

I am encountering an issue in my Node.js app where MongoDB is causing objects to be reordered when inserting new records into the database. I am using the following insert method: collection.insert(object, {safe:true}, function(err, result) { if (err) ...

Creating two separate divs that can scroll independently while also limiting each other's scroll depth can be achieved by utilizing

I am attempting to replicate the unique scrolling feature seen on this particular page. Essentially, there are two columns above the fold that can be scrolled independently, but I want their scroll depths to be linked. When a certain depth is reached whil ...

When using jQuery, the PHP variable value is not retrieved from the DIV data-id attribute, instead it just displays the variable name

I currently have the following code: <div class= "obutton feature2" data-id=".$bookID."><button>Reserve Book</button></div> <div class="modal-box"></div> Although this button triggers the jQuery script, the modal box ...

implementing CORS on an Express server for a specific domain

I am attempting to send a cookie post-login via AJAX from my localhost to a server that is hosted elsewhere. In order to prevent any errors related to cookies, I have included the following code in my Axios setup: var instance = axios.create({ withCr ...

Using javascript to store HTML tags in a variable

Hey there, I have a quick question. Can someone help me figure out why this code isn't working? let plus = "+" + '<h1>'+"This is a heading"+'</h1>'; When I run the code, the output I get is: +<h1 ...

The process of sending JSON data to a Vue instance

I am facing an issue with my Vue instance where I need to pass JSON data from the backend without using HTTP requests because the data is constant. I attempted to achieve this using props, but encountered some challenges... In the DOM, it appears as <d ...

Exploring jQuery Mobile - What Causes an Empty State?

Using $.mobile.navigate("#test-page", {id:123}) for navigation to a secondary page seems to be successful. The transition between pages is smooth.... but the state remains empty! According to the documentation, the state should contain all necessary info ...

responsive cascading dropdown.. preassigned value

I've come across this interesting script on a website and it's been working pretty well for me so far. The script can be found at the following link: . However, I have a specific requirement when it comes to setting a certain value for the catego ...

Encountering a problem with Chrome Extension localization upon installation - receiving an error message claiming default locale was not specified, despite having

Error Message: "The package has been deemed invalid due to the following reason: 'Localization was utilized, however default_locale was not specified in the manifest.' Issue: I have developed a customized extension and defined a default locale, ...

Top destination for verifying permissions in vue.js

Within my Laravel/vue.js application, the initial page load results in a structure like this: <script> window.settings = {}; window.settings.user = {}; window.settings.user.timezone = 'Europe/Moscow'; w ...

What is the best way to minify and concatenate multiple CSS files only after converting SCSS to CSS with Gulp?

When attempting to convert my scss files to css files using gulp, I encountered an issue. After writing the scss code, it is easily converted to css. However, I wanted to minify this css and save it in a different folder called 'min'. Within the ...

Error: The variable "Set" cannot be found in the react.js code, specifically in Safari browser

An issue has been identified in Safari where a ReferenceError is thrown: "Can't find variable: Set" when using react.js. This error occurs only in Safari, while all other browsers work perfectly fine. The error message points to the main.js file which ...

Issue with Angular $compile directive failing to update DOM element

I'm currently working on a project that involves integrating AngularJS and D3 to create an application where users can draw, drag, and resize shapes. I've been trying to use angular binding to update the attributes and avoid manual DOM updates, b ...

Ending the Firefox browser using JavaScript

I have been trying to use the basic window close javascript command window.close(); but it seems to only work in IE and not in any other browser. Can anyone provide assistance on how to successfully close a browser tab in Firefox, Opera, or Chrome? Thanks ...

Add Firebase Data to Dropdown

Utilizing Vuetify to build a dropdown has been an interesting challenge for me. While I can successfully select a value and store it in the firebase database, I'm facing difficulties when it comes to repopulating the dropdown after page refresh. Belo ...

Tips for retrieving values from numerous checkboxes sharing the same class using jQuery

Currently, I am struggling with getting the values of all checkboxes that are checked using jquery. My goal is to store these values in an array, but I am encountering difficulties. Can anyone provide me with guidance on how to achieve this? Below is what ...

It is likely that the variable is out of scope and is undefined

I have a piece of code that retrieves the description of a word in JSON format from website, which is provided by the user in the request JSON body. The issue I'm facing is that I am unable to send back the 'desc' variable in the res.send ...

Enhancing the Rendering of React's props.children

I have set up my code like this: // Parent.js class Parent extends React.Component { render() { return { this.props.children } } } // Child.js class Child extends React.Component { render() { let message; const greet = ...