Having trouble with JavaScript's array sorting function

Currently, I am attempting to organize an array of objects based on the attribute page, and I am doing this within a computed property using Vue.

The function I am utilizing involves building the objects in the following manner:

 sorted: function(){
     var pages = this.selectedKKS['pages'];
     var list;
     try {
       list = [];
       Object.keys(pages).forEach(function(key){
         console.log(key + " is the key")
         var obj = {};
         obj.title = key;
         obj.page = pages[key]
         list.push(obj)
     });         
     }
     catch(e){
       console.log(e);
     }
     var sorted = list.sort(function(a, b){
       console.log('a.page is ' + a.page + ' and b.page is ' + b.page);  
       return a.page > b.page;  

     });
     return sorted;      
 }   

To ensure that my comparisons of pages are accurate, here is the output from the console log:

a.page is 84 and b.page is 28
App.vue?077f:353 a.page is 84 and b.page is 46
App.vue?077f:353 a.page is 28 and b.page is 46
App.vue?077f:353 a.page is 84 and b.page is 35
App.vue?077f:353 a.page is 46 and b.page is 35
App.vue?077f:353 a.page is 28 and b.page is 35
App.vue?077f:353 a.page is 84 and b.page is 14
App.vue?077f:353 a.page is 46 and b.page is 14
App.vue?077f:353 a.page is 35 and b.page is 14
App.vue?077f:353 a.page is 28 and b.page is 14
App.vue?077f:353 a.page is 84 and b.page is 5
App.vue?077f:353 a.page is 46 and b.page is 5
App.vue?077f:353 a.page is 84 and b.page is 8
App.vue?077f:353 a.page is 5 and b.page is 8

As I am iterating over this computed property in my template, it seems like the sorting is not being done correctly, resulting in an unintended outcome:

            <f7-list>
            <f7-list-item v-for="val in sorted" @click="openpdf(selectedKKS.url, val.page)">                    
                <f7-col><span style="color: black">{{ val.title }}</span></f7-col>                      
                <f7-col>{{ val.page }}</f7-col>                 
            </f7-list-item>
            </f7-list>

https://i.sstatic.net/alKdS.png

Could anyone provide insight into what might be causing this issue? Any suggestions would be greatly appreciated.

Answer №1

Since the data values are in string format, they will be sorted alphabetically instead of numerically.

To fix this issue, update your sorting function like this:

list.sort(function(a, b){
    return Number(a.page) > Number(b.page);  
});

Alternatively, you can use:

list.sort(function(a, b){
    return Number(a.page) - Number(b.page);  
});

It's advisable to convert the values to numbers when creating the objects to avoid repetitive conversions during comparisons.

Answer №2

Instead of using '>', try '-' in the sorted function like this..

var sorted = list.sort(function(a, b){
   console.log('a.page is ' + a.page + ' and b.page is ' + b.page);  
   return a.page - b.page;  
 });

I hope this suggestion proves to be helpful!

Answer №3

When creating a callback function for sorting, it is important to remember that it must return an integer. If the comparison results in less than 0, the function should return -1; if it is equal to 0, then the function should return 0; and if it is greater than 0, the function should return 1.

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

Creating an embedded link to a website that adjusts to different screen sizes while also dynamically changing

I've been developing a personalized site builder that includes an iframe for previewing responsive websites. In order to make the site 'zoomed out' and not appear in mobile size, I'm utilizing CSS scale and transform origin as shown bel ...

Mapping JSON data with an elastic search cluster can be challenging, especially when dealing with a dynamic number of fields

I am currently developing an application where I need to map JSON data for storage in Elasticsearch. The challenge is that the number of fields in the JSON data is dynamic. How can I handle mapping in this scenario? Mapping Snippet var fs = uploadedFiles ...

Iterating through two arrays simultaneously in Java using the foreach loop

Is it possible to achieve this in Java? I have a straightforward question: ArrayList<String> arr1 = new ArrayList<String>(); ArrayList<String> arr2 = new ArrayList<String>(); // Processing arrays, filling them with data for(Strin ...

rectangle/positionOffset/position().top/any type of element returning a position value of 0 within the container

While the height/position of the container is accurately displayed, attempting to retrieve the top position (or any position) of containing elements yields a return value of 0. Additionally, using .getBoundingClientRect() results in all values (top, left, ...

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...

Transferring a parameter from link_to to a popup window in a Rails application

I am facing an issue with passing an object to my modal in Rails. The object has a table of results with an attribute "email", but I seem unable to pass it so that I can use it within my modal. index.html.erb <div class="modal fade bs-example-modal-lg ...

Using Spring MVC and Thymeleaf to dynamically load new HTML pages on ajax calls

Hello there, I'm looking to dive into using thymeleaf for my web application. My goal is to create a simple website with HTML pages. Below is the URL of my landing page controller that returns the index.html page: @RequestMapping("/index") public Str ...

"Trying to access jQuery .slide and .slideUp features, but unfortunately they are

I've created this script: $("#comments .comment .links").hide(); $("#comments .comment").hover( function() { $(".links", this).stop(true).slideDown(300); }, function() { $(".links", this).stop(true).slideUp(300); } ); However, I'm facin ...

Unfortunately, I am currently unable to showcase the specifics of the items on my website

I am trying to create a functionality where clicking on a product enlarges the image and shows the details of the product as well. While I have successfully implemented the image enlargement, I am facing challenges in displaying the product details. Below ...

Issue: Attempting to render objects as React children is invalid. Consider using an array if you want to render a collection of children. This problem often occurs when fetching data from a JSON

Hey everyone, I'm currently working on a small website using ReactJS. After adding the code below, an error keeps popping up: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead. Here's t ...

FullCalendar, showcasing real-time event creation as you select dates

I am currently utilizing fullcalendar 4 on my website and I am attempting to incorporate an indicator for when a user selects a date on the calendar. While the background color changes, it's not very visible. My aim is to replicate the functionality ...

Iteratively applying a vector function to populate a matrix

I've been experimenting with a function that generates a row vector (N) up to a specified number of N columns. The vector is created by starting with a random integer between 1 and 5 for the first column, and then adding a random integer between 1 and ...

What is the best way to integrate an array from an external JavaScript file into a Vue.js component?

I am struggling to import an array into a Vue component: This is my simplified component: <script type="text/babel"> const codes = require('./codes.js'); export default { props: [], data() { return { ...

Response from the controller upon choosing a value from the selection dropdown

Scenario: In this scenario, there are two tables in consideration: Firm table : ID (string), Firm(string) Firms table: FirmID(string FK), Name(string) The goal is to select a value from the Firm table, pass it to the controller as Firm, and then execut ...

Progress bar for AJAX file loading for Flash player

Looking to create a progress bar using AJAX for a flash file. Check out this demo here: I tried to analyze their page, but the JavaScript is encrypted and I'm not very skilled in JS. Any suggestions? Thank you! ...

What causes a useState to revert back to false when navigating back and forth on the screen?

Recently, I've been working on a feature to toggle favorite products and store their unique id along with an isFav property on a Firebase database. This data is then used to display the favorites on the FavoritesScreen. While testing this functionali ...

Content that is dynamically generated by a database

I have been working on creating a unique wall feature for my website, inspired by Facebook. My aim is to allow users to submit form data and have it validated before storing it in a database. Additionally, I want this stored data to be displayed in a desig ...

Difficulty arising from commands

I am currently familiarizing myself with the use of directives in AngularJS. I have a password.html file that contains an input field for passwords, and I have created a custom directive called 'passwordRequirement' to enforce specific requiremen ...

Can you effectively link together AngularJS promises originating from various controllers or locations?

Attempting to explain in as much detail as possible, the configuration file config.js contains the following code snippet: .run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $loca ...

Utilizing a custom keyboard with Jquery for a recurring function

It seems like I might be missing something simple here, as I am following the code tutorial provided in the link below: The goal of this project is to create a popup keyboard for a touch screen. Although I have made some modifications for specific purpose ...