Having issues with Element UI sorting values in a table

I've been attempting to create a basic sorting function, but it doesn't seem to be functioning correctly.

var Main = {
  data() {
    return {
      tableData: [{
        value: '1.799,37',
        name: 'Tom 3'
      }, {
        value: '2.183,88',
        name: 'Tom 2'
      }, {
        value: '3.837,05',
        name: 'Tom 4'
      }, {
        value: '769,8',
        name: 'Tom 6'
      }, {
        value: '111,8',
        name: 'Tom 6'
      }, {
        value: '999,8',
        name: 'Tom 6'
      }]
    }
  },
  methods: {
    test: function(a, b) {
      return a.value - b.value;
    }
  }
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
@import url("//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88ede4ede5ede6fca5fde1c8b9a6bba6bc">[email protected]</a>/lib/theme-default/index.css");
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d2dbd2dad2d9c39ac2def78699849983">[email protected]</a>/lib/index.js"></script>
<div id="app">
  <template>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column prop="value" label="Value" sortable :sort-method=test width="180"></el-table-column>
    <el-table-column prop="name" sortable label="Name" width="180"></el-table-column>
  </el-table>
</template>
</div>

Answer №1

 function sortAlphabetically(x,y) {
        if (x.title.toUpperCase() <  y.title.toUpperCase()) return -1;
       if (x.title.toUpperCase() > y.title.toUpperCase()) return 1;
       return 0;
 }

Answer №2

Within your array named tableData, each object includes a value which is represented as a string. Your current sorting method compares strings, but it seems that you actually want to sort them numerically.

To achieve this, you need to update your method like so:

methods: {
  test: function(a, b) {
    return this.toFloat(a.value) - this.toFloat(b.value)
  },
  toFloat: function(num) {
    return parseFloat(num.replace('.','').replace(',','.'))
  }
}

It's worth noting that the replace function is used to ensure that your strings are interpreted as valid numbers

var Main = {
  data() {
    return {
      tableData: [{
        value: '1.799,37',
        name: 'Tom 3'
      }, {
        value: '2.183,88',
        name: 'Tom 2'
      }, {
        value: '3.837,05',
        name: 'Tom 4'
      }, {
        value: '769,8',
        name: 'Tom 6'
      }, {
        value: '111,8',
        name: 'Tom 6'
      }, {
        value: '999,8',
        name: 'Tom 6'
      }]
    }
  },
  methods: {
    test: function(a, b) {
      return this.toFloat(a.value) - this.toFloat(b.value)
    },
    toFloat: function(num) {
      return parseFloat(num.replace('.','').replace(',','.'))
    }
  }
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
@import url("//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c191019111912085109153c4d524f5248">[email protected]</a>/lib/theme-default/index.css");
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2e272e262e253f663e220b79657b657a7a">[email protected]</a>/lib/index.js"></script>
<div id="app">
  <template>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column prop="value" label="Value" sortable :sort-method=test width="180"></el-table-column>
    <el-table-column prop="name" sortable label="Name" width="180"></el-table-column>
  </el-table>
</template>
</div>

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

Overlapping background images of flex elements in Safari

This webpage is designed as a single-page layout using Gatsby: <div className='mainContent'> <section className='contentSection'> <h1 className='header'>Heading</h1> <div c ...

Coloring the table upon selecting a checkbox using AJAX, JavaScript, and JSP

How can I adjust the color of the entire table (every row of the table)? Currently, I can only change the color of the first row of my table. Here is my color function in JSP: function changeColor(rowID){ var row = document.getElementById(rowID); ...

Whenever I try to open my jQuery UI Dialog without first displaying an alert, it does not work

Beginning of my HTML page, initializing a dialog : <script type="text/javascript"> $(function() { $( "#dialog-confirm" ).dialog({ autoOpen: false, resizable: true, height:180, width:300, modal: true, buttons: { "Yes": ...

Exploring the implementation of constructors and classes in JavaScript

I have a task to create a class named ShoppingCart with specific instructions: The class should have a constructor that initializes the total attribute to zero and creates an empty dictionary attribute called items. There should be a method named add_ite ...

Optimize your mobile experience by creating a notification menu that is scrollable and fixed in position

Recently, I purchased Moltran, but encountered a major issue: The notification menu disappears on mobile devices, which is not ideal for me. After some research, I discovered that removing the hidden-xs class from the li notification element can solve this ...

Creating a function in Javascript to adjust opacity when clicked

I am looking to create a function that controls opacity when a particular element is clicked. I tried the following code, but it did not have the desired effect. var changeOpacity = function(id) { document.getElementById(id).style.opacity = "1"; }; ...

Retrieving Outdated Information through the Express Framework

Whenever I make a fetch request to a node express server, it sometimes returns old data that was previously fetched from the same endpoint. This issue occurs sporadically but seems to happen more often than not. Even after disabling Cache-Control in the f ...

Deploying a Nuxt web application using Azure pipelines

Thank you for taking the time to read this. I've been facing challenges while trying to deploy a Nuxt application correctly. To troubleshoot, I created a fresh Nuxt application to ensure that my codebase is not the issue. My main objective is to push ...

Continue looping in Javascript until an empty array is identified

Currently, I am in search of a solution to create a loop in Javascript that continues until the array of objects is empty. The object I am working with looks like this: "chain": { "evolves_to": [{ "evolves_to": [{ ...

Is it possible to synchronize Vue data values with global store state values?

I need help updating my data values with values from store.js. Whenever I try the code below, I keep getting a blank page error. Here's how I have it set up in App.vue: data() { return { storeState: store.state, Counter: this.storeState.C ...

The request for the option was unsuccessful due to a 404 error

I'm facing an issue with sending a GET request from my frontend to an API application, both running on my local machine. The setup looks like this: backend <===> frontend <=x=> API application Each component runs in its own docker contai ...

Issue with React: Children's state is altering the state of the parent component

Question : Why is it possible for a child component to change the state of its parent when each component has its own state? Below is the complete code for my app: import React, { Component } from 'react'; import { render } from 'react-do ...

Using finally() to correctly construct a Javascript promise

Currently, I am working on an Express API that utilizes the mssql package. If I neglect to execute sql.close(), an error is triggered displaying: Error: Global connection already exists. Call sql.close() first. I aim to keep the endpoints simple and e ...

Nuxt Vue's new feature integrates Mermaid support for enriched content creation

After following the recommended steps, I attempted to integrate mermaid support into my Vue application. The process is outlined here If you'd like to see a demo, it's available here Utilizing Mermaid.vue <template> <div class=&quo ...

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...

Encountering issues with AJAX requests using jQuery

Hey there, I'm attempting to make an AJAX call in a C# page and I'm running into some issues. Below is my jQuery code: $(document).ready(function () { $.ajax({ type: "POST", url: "conteudo.aspx/GetNewPost", data: { i ...

Looking for a way to access the source code of a QML method in C++?

I'm currently working on serializing objects to QML and I am looking for a way to retrieve the source code of functions defined within a QML object. Let's consider the following example in QML (test.qml): import QtQml 2.2 QtObject { functio ...

The ideal formats for tables and JavaScript: How to effectively retrieve arrays from a table?

Given the task of defining a function that extracts the mode of weights from an HTML table containing age and weight data for individuals within a specified age range. The function needs to be able to handle tables of any size. I am looking for the most ef ...

NPM: The registry cannot be found

npm http GET https://registry.npmjs.org/n npm ERR! Error: failed to fetch from registry: n npm ERR! at /usr/share/npm/lib/utils/npm-registry-client/get.js:139:12 npm ERR! at cb (/usr/share/npm/lib/utils/npm-registry-client/request.js:31:9) npm ERR ...

I have implemented a bootstrap modal, but whenever I trigger a function on the JavaScript side, it automatically closes. I am aiming for the modal to remain open

<div id="responsive-modal3" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none; " data-keyboard="false" data-backdrop="static" ng-init = "populateBidSpocData()" > <div cl ...