Sorting cryptocurrency prices using Vue.js is causing issues

I've been encountering an issue with the sort() method and I'm having trouble solving it. Essentially, I have a table displaying cryptocurrency data fetched from an API, and it has the ability to sort each column. Everything seems to be working fine for columns like Rank, Name, and MarketCap, except for the Price column. It doesn't seem to sort correctly - for instance, the price of BTC always ends up somewhere in the middle. The prices retrieved from the API are in String format.

Here's a photo of the cryptocurrency table

Below is the sorting method I am currently using:

 sortBy (prop) {
  if (this.sorter === 'inc') {
    this.cryptos.sort((a, b) => a[prop] > b[prop] ? 1 : -1)
    this.sorter = 'dec'
  } else {
    this.cryptos.sort((a, b) => a[prop] > b[prop] ? -1 : 1)
    this.sorter = 'inc'
  }
},

And here is how I invoke the sorting method in the table:

 <tr>
    <th class="table-header table-link" v-on:click="sortBy('rank')">Rank</th>
    <th class="table-header">Icon</th>
    <th class="table-header table-link" v-on:click="sortBy('name')">Name</th>
    <th class="table-header">Symbol</th>
    <th class="table-header table-link" v-on:click="sortBy('price')">Price</th>
    <th class="table-header table-link" v-on:click="sortBy('change')">{{time}}</th>
    <th class="table-header table-link" v-on:click="sortBy('marketCap')">Market Cap</th>
 </tr>

Sample amounts received from the API (remember they are in String format):

464.2807003746
15150.0527417405
0.5010685149
0.8374992554
0.5010685149 
66.5544823869
233.8180345945
4.2255392708
10.9344985436
0.1363374574
0.16150966

I hope that provides enough information, and I would greatly appreciate any assistance on this matter. Thank you in advance!

Answer №1

.sort() is a method that arranges strings in lexicographical order, comparing each character one by one. If you are dealing with numbers disguised as strings, it is important to convert them into actual numbers before sorting.

// Sorting strings example
[
  `464.2807003746`, 
  `15150.0527417405`, 
  `0.5010685149`
].sort((a, b) => a > b ? 1 : -1)
//=> [('0.5010685149', '15150.0527417405', '464.2807003746')];

// Converting strings to numbers before sorting
[
  `464.2807003746`, 
  `15150.0527417405`, 
  `0.5010685149`
].sort((a, b) => Number(a) > Number(b) ? 1 : -1)
//=> "0.5010685149", "464.2807003746", "15150.0527417405"]

// Implicit conversion of strings to numbers before sorting
[
  `464.2807003746`, 
  `15150.0527417405`, 
  `0.5010685149`
].sort((a, b) => a - b)
//=> "0.5010685149", "464.2807003746", "15150.0527417405"]

If you have a custom sortBy method, make sure to include a condition to check if the property being sorted is a price value.

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

Efficiency levels of reach = within angular instructions

Creating a directive can be done in various ways. Here is an example of how I structured mine: 'use strict'; myApp.directive('mySwitchOnOff', [ '$rootScope', function($rootScope) { return { restrict: 'C' ...

Guide on developing a library that exposes a Vue component for consumption in a distributed .mjs file

Creating a Vue component that is bundled into a single .mjs file for consumption by another Vue project via HTTP is my goal. Due to runtime configuration requirements, npm installation of the pluggable component is not an option. Key considerations for th ...

Please input only 0s and 1s into the designated field

How can I modify this code to only accept 0 and 1 in the input field, while also adding spaces after every 4 digits? Currently, it accepts all digits. I'm struggling with creating a pattern that restricts it to just 0 and 1. document.getElementById(&a ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

Issue with Bottle.py: When using AJAX, request.forms.get() is returning NoneType

Having trouble sending JavaScript data to a bottle.py server using AJAX? Despite trying numerous solutions from various sources, none seem to be working. To provide clarity, I'm focusing on the AJAX call code here. Can someone explain why request.for ...

Obtain user input from a form and assign it to a variable in a jQuery AJAX

How can I pass the value of an HTML Input Form to a jQuery AJAX call's URL as `amt` in `url: "http://localhost:8080/orderNo?amount=" + amt,`? The input value logs to the console when calling getAmtValue(), but I'm struggling to access the `amt` ...

Conceal all elements until a search query is entered using the search bar

I want to create a search bar that hides all elements until the user actually searches for them, you can check out my JSfiddle for reference: `JSfiddle Link <div id="search"> <form> <input type="text" name="search" id="m ...

Is there a way to extract values from a particular object?

Currently, I am utilizing a JSON server to establish a straightforward login system. The data stored on the server is structured as follows: { "users": [ { "name": "user1", "password": "pass1", "email": "<a href="/cdn-cgi/l/emai ...

Creating an array of future dates using Moment.js

I am trying to use moment.js to create an array of the next 12 months, starting from the current month. For example, let's say the current month is December: var monthsArray = [ "December", "January", "February", "March", [...] "November" ...

Developing Dynamic Key-Driven State Management in ReactJS Using JavaScript

I am facing a challenge with a specific aspect of my ReactJS code, which is more about my comprehension of how JavaScript key/value arrays operate than anything else. How can I allow the key to be passed-in dynamically in the given example? The issue lies ...

I continuously receive the error message "StripeInvalidRequestError: Insufficient funds in Stripe account" despite the fact that there are adequate funds available

I'm in the process of transferring funds from my test mode Stripe account to another connected Stripe account. The balance in my test mode account is sufficient and there are no pending funds. However, I keep encountering a "StripeInvalidRequestError: ...

Enhancing a popup with animated effects

I have been working on a popup that I want to add a subtle animation to. A fade effect seems like the perfect solution. Here is the code for the button: <a href="javascript:void(0)" onclick="document.getElementById('back_overlay').style.disp ...

Examining the potential of a promise within a dynamic import feature in Angular

Here's a code snippet that I'm working with: The component file (component.ts) looks like this: async ngOnInit() { import('dom-to-image').then(module => { const domToImage = module.default; const node = document.getEl ...

Extract image file name and date information (day, month, year) from an HTML form using Angular

The content of the register.component.ts file can be found below: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: [&apo ...

Guide on integrating Vue.js with Sails.js

I attempted to set up Vue.js as the frontend for Sails.js by following the method outlined in this blog post: . However, I encountered issues with the latest version of Vue. I'm unsure why this is happening – can anyone clarify why it's not wor ...

When using Browsersync in a single page application, an "Refused to execute inline script" error may occur if the route is not at the root level

I encountered the following error while using my Vue SPA: Refused to execute inline script due to Content Security Policy violation with directive "default-src 'self'". To allow inline execution, use 'unsafe-inline', a hash ('sha2 ...

Using the ngrx signalStore within the facade design pattern - a step-by-step guide

How can I utilize ngrx's new signalStore in Angular to fetch locations of arms, save them in the state, and replace a service with LOCATION_STORE after setting the locations on a map with markers? The challenge lies in waiting for the response of loca ...

Navigate through an overflowing element in react/next

I have a component with a fixed width and overflow-x-auto. I want to hide the scroll bar and replace it with arrow buttons for scrolling left and right. How can I add this functionality to my component? Here is the code for my component: <div className ...

The resolveMX function in Google Cloud Functions is encountering issues when trying to process a list of domains

Here is the task at hand. I have a large list of domains, over 100,000 in total, and I need to iterate through them using a foreach loop to resolve MX records for each domain. Once resolved, I then save the MX records into another database. Below is the c ...

Obtaining Spotify API access token using JavaScript code on the front end

I've developed a web application that enables users to generate a list of songs by artists related to a selected artist. The goal is to link the user's Spotify account and create a playlist based on this generated song list, which requires obtain ...