Arranging in descending order after computing percentage within a v-for loop

Using Vue.js to calculate percentages, consider the following code snippet:

  <tr>
    <span v-for="(item, index) in data.values" :key="index" >
      {{ item.name }} {{ getPercentage(item.nr) }}
    </span>
  </tr>

Here's the method to calculate percentage:

methods: {
  getPercentage (number) {
    return number / this.nrUsers * 100; // Ignore the logic for now
  }
}

The calculation of percentage values is correct, but the issue arises when displaying them. Sorting in descending order is desired, and since the calculation happens here, backend sorting seems challenging. Any suggestions on how to achieve descending sorting in Vue.js?

Answer №1

Consider utilizing a computed property in place of a method:

const app = Vue.createApp({
  data() {
    return {
      items: [{id: 1, nr: 5, name: 'aaa'}, {id: 5, nr: 15, name: 'bbb'}, {id: 2, nr: 7, name: 'ccc'}, {id: 3, nr: 24, name: 'ddd'}, {id: 4, nr: 25, name: 'eee'}],
    };
  },
  computed: {
    sortedItems() {
      return this.items.map(item => {
        let pct = item.nr / 100 * this.items.length;
        return { ...item, pct }
      }).sort((a, b) => b.nr - a.nr)
        
    }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <li v-for="(item, index) in sortedItems" :key="index" >
      {{ item.name }} {{ item.pct }}
    </li>
</div>

Answer №2

Sorting the items when rendering is not possible. You must first sort your data in descending order before rendering.

If you follow the steps mentioned in your comment, you will be able to sort the items efficiently.

  1. Retrieve the data from the API.
  2. Iterate over the data items and calculate their percentage.
  3. Arrange the data in descending order based on the percentage value.
  4. Finally, display this sorted data in the template.

Hopefully, these instructions guide you in the right direction.

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

Each loop in the forEach function triggers the mouseup event

I am currently utilizing a foreach loop: objects.forEach(function(object) { var button = '<tr><td>' + object.object.code + '</td><td>' + formatDistance(1456000) + &apos ...

Ways to retrieve parameters in the following function using Express

I need help accessing fromFlight and toFlight variables in the next function that I have defined. Currently, I am only getting the output of the entire req object. Can someone assist me with this issue? Below is a snippet of my code: const express = requ ...

How can I toggle specific v-if divs within a v-for loop in Vue.js?

I would like to implement a feature where each post in a loop has a dropdown menu that can be shown/hidden when clicked: <div v-for="(post, index) in posts" :key="index" > <div v-on:click.prevent="toggleDropDown(post)">Show/hide menu & ...

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...

Encountering an error while attempting to map a collection in React JS - the value is

Within my state, I have a collection set up like this: getInitialState: function() { return { studentId: 666, activeTabId: 1, sections: [ {name: 'were', value: 1, label: 'Basic Details'}, {na ...

Loading V-Select with Data from JSON Using Vue.js

I tried to populate my v-select multiselect element using a JSON object, but unfortunately it did not work as expected. Here is the result I encountered: https://i.sstatic.net/kd1Gl.png <v-select v-model="serviceValues" :items="serviceO ...

Experiencing excessively rapid zooming in JavaFX Leaflet on WebView

Incorporated a Leaflet map into my JavaFX project, but encountered a zoom speed issue. When I zoom in by one step, it zooms all the way to the size of Iceland: https://i.sstatic.net/BkReA.jpg The expected behavior is for the map to zoom in just slightly: ...

Guide to adding the initial element in an array using Immutability Helpers

Looking to rearrange the elements in an array? The challenge is that it involves a link to the object. How can this be achieved using immutability helper? Below you will find my current code: state = { table: [['', '', ' ...

What is the best way to organize, truncate, and transform elements in an array?

Trying to rearrange the array, then display only the last n elements, and finally map it. Here is the current working version (in react syntax) with sorting and mapping, missing the slicing part: {Object.keys(dataObj) .sort( ...

Changing text array to field identifiers with JavaScript

Is there an elegant way in ECMAScript 6 to transform a string array generated from a map function into field names within a dynamically created object? For instance, if I receive the following output from my map function: ["checkbox1Value", "checkbox4Val ...

Managing the verification of data existence in the ExpressJS service layer or controller

Working on a medium-sized website, I realized the importance of writing maintainable code with a better project structure. After stumbling upon this insightful article and some others discussing the benefits of 3-layer architecture, I found the concept qu ...

Organizing your web application directories with AngularJS and Node.js

As I dive into the world of learning node.js and angularjs, I find myself struggling with how to best organize and structure my folders and their contents. Despite coming across some existing questions on this topic, none have provided a solution that trul ...

Steps for launching a pop-up window in a response asynchronously

Hey there, I'm currently facing an issue with rendering a modal when my API response contains an error. Do you have any alternative suggestions on how to display a modal every time the API returns an error? const useEmbedContent = (resourceId) => { ...

Updating an object within an array of objects can be achieved by utilizing the setState method in React

I'm currently working with React, where my state is structured as an array of objects. I'm looking for a way to specifically update only one element in the state.data array, such as the object with id 1. I'm curious about: how to properly ...

Access a remote server via SSH and run Node.js commands

I need assistance with SSHing into a virtual machine and running scripts within it using Node.js Currently, I have a shell script that handles the login process to the virtual machine, but I'm stuck on what to do next. This is the shell script I&apo ...

When values are deleted from an array object, the entire structure is altered even when browsing through the keys

Manipulating arrays within objects: -----code ------- var obj1 = { 'a': ['a','b','c','d'], 'b':['b','d','r','a']} Object.keys(obj1).forEach(element =& ...

Is it possible to execute an npm package without using the npm run command?

Is there a way to initiate the next.js build process directly through the command line without needing to use the package.json file? Can we execute it without relying on npm run? Perhaps running next build in the command line could achieve this instead of ...

Is it possible to enlarge a div using "display: table-cell" property when clicked on?

There are various components displayed on my webpage: I require all components to have a minimum height of 150px. If the height is less than 150px, I want to vertically center their text. In case the height exceeds 150px, I aim to truncate the text at 15 ...

JSON Attribute Name Escaping

Can't figure out how to escape attribute name in Lambda function { "statusCode": 200, "body": { "Customer_Code": "CCode", "c_type_/_customer_type": "Customer Type" } } Noticing the use of & ...

The stunning fade effect of Magnific Popup enhances the visual appeal of the inline gallery

I'm currently using magnific popup for an inline gallery, but I'm not seeing any effects. I would like to have a fade effect when opening/closing the popup. Can someone assist me with achieving this? https://jsfiddle.net/gbp31r8n/3/ [Check o ...