Sorting custom data in a Vue data table, prioritizing null values to be displayed

Currently, in my VueJS v-data-table setup, I am facing a challenge with custom sorting functions. The table has both numeric and string columns, with some null values scattered throughout. My goal is to sort the data by placing null values at the end of each column.

<v-data-table
        :headers="[
          { text: 'Name', value: 'name' },
          { text: 'Date of Birth', value: 'dateofbirth_fmt' },
          { text: 'Team', value: 'team_name' },
          {
            text: 'dp1 (string)',
            value: 'dp1',
          },
          {
            text: 'dp2 (Numeric),
            value: 'dp2',
          }
        ]"
        :items="filteredPlayersData"
        item-key="_id"
        class="elevation-1"
        :custom-sort="customSort"
      />

I have implemented the following function:

customSort(items, index, isDesc) {
      items.sort((a, b) => {
        if (!isDesc[0]) {
          return (a[index] != null ? a[index] : Infinity) >
            (b[index] != null ? b[index] : Infinity)
            ? 1
            : -1;
        } else {
          return (b[index] != null ? b[index] : -Infinity) >
            (a[index] != null ? a[index] : -Infinity)
            ? 1
            : -1;
        }
      });
      return items;
    }

While this works for sorting the numeric column (dp1), it does not perform as expected for the string column (dp2). Any suggestions on how to improve the functionality for sorting strings with null values?

Answer №1

Your current sorting algorithm does not handle strings correctly.

Consider a scenario where the first string is null, and the second one is 'Jelly bean'. Instead of comparing null with 'Jelly bean', the algorithm is attempting to compare Infinity with 'Jelly bean'.

This comparison will result in false in both cases:

let a = Infinity;
let b = 'Jelly bean';
console.log(a > b);
console.log(a < b);

It would be more appropriate to implement a different sorting algorithm.

For instance, you can utilize an algorithm that has been modified from this post:

customSort(items, index, isDesc) {
  items.sort((a, b) => {
    if (a[index] === b[index]) { // equal items sort equally
      return 0;
    } else if (a[index] === null) { // nulls sort after anything else
      return 1;
    } else if (b[index] === null) {
      return -1;
    } else if (!isDesc[0]) { // otherwise, if we're ascending, lowest sorts first
      return a[index] < b[index] ? -1 : 1;
    } else { // if descending, highest sorts first
      return a[index] < b[index] ? 1 : -1;
    }
  });
  return items;
}

You can test this sorting algorithm on CodePen by following this link: CodePen. It works effectively for sorting both strings and numbers.

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

Operating on Javascript Objects with Randomized Keys

Once I retrieve my data from firebase, the result is an object containing multiple child objects. myObj = { "J251525" : { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c3823212 ...

Switch up the linear gradient background periodically

Is there a way to change the background after a certain amount of time? It seems to work fine if the background color is just a solid color, but when it's a gradient as shown in the code below, the solution doesn't seem to work. Any suggestions f ...

Building web navigation using a combination of HTML, JavaScript, and PHP within a category, sub

I've been struggling to find a detailed tutorial on implementing a dynamic website navigation system using javascript or php. It seems like every time I attempt to research this topic, I end up feeling confused and unsure of where to start. My goal i ...

Utilizing JQuery to extract data from a <select> dropdown menu

Is there a way to retrieve the current value of a SELECT tag using JavaScript or jQuery? I have tried using $('select').val(), but it only returns the default value and does not update when changed. Any suggestions on how to solve this issue? $( ...

Is there a way to determine the orientation of an image in React-Native, whether it is horizontal or vertical

When working with react-native, I aim to utilize the 'contain' feature for vertical images and the 'stretch' feature for horizontal images. What would be the best way to determine the orientation of an image as either horizontal or vert ...

Unable to track user (Mineflayer - Node.js)

Trying to track a player using the mineflayer library in Node.js, but encountering an error within the source code of the library itself. Attempted code: const mineflayer = require('mineflayer'); const { pathfinder, Movements, goals } = require( ...

Generate a configuration file that allows for the reading and storage of modifications

Is there a way to create a configuration file (JSON) on the local file system using JavaScript where I can write and modify data without losing it when the application is restarted? Any suggestions or solutions for this problem? Thank you for your assista ...

The dynamic routing feature in React fails to function properly after the application is built or deployed

I'm facing an issue with getting a React route to function properly in the build version of my app or when deployed on Render. Here are the routes I have: <Route path="/" element={userID ? <Home /> : <Login />} /> <Route ...

Function utilizing variables parsed by Angular directive

I am currently working on a directive that I have created: feedBackModule.directive("responseCollection", ['deviceDetector', function (deviceDetector) { return { restrict: "E", templateUrl: 'js/modules/Feedback/direc ...

Issue with returning value from promise object in Next.js

Hello! I am fairly new to JS and React, so I would appreciate your patience as I try to navigate through this. It has been quite a journey so far. In my component, I am fetching JSON data from a URL and attempting to extract a specific value from it to d ...

I am encountering an issue with express-session where it is failing to assign an ID to

Seeking assistance with utilizing express-session to manage user sessions on arcade.ly. I have not specified a value for genid, opting to stick with the default ID generation. However, an ID is not being generated for my session. An example of the issue c ...

Encountering the issue of receiving an undefined value for Props in a

I'm facing an issue where I am trying to pass a data property from the parent component to the child component as a prop. However, in the child component, the value of the prop is displaying as undefined. <template> <companyInfo :limit="this ...

Tally each div individually and display the count within each div, instead of showing the total count across

I have come across various solutions that show the total number of certain special divs, such as: $('.someclass').length However, I am facing a different challenge. I want to sequentially count each div with a numerical sequence. For instance, ...

Is there a way to make Phpstorm identify and acknowledge the usage of NextJS pages?

Just finished setting up my brand new NextJS app: function MyApp({ Component, pageProps }: AppProps) { return ( <Layout> <Component {...pageProps} /> </Layout> ) } export default MyApp However, PHPStorm keeps giving me ...

Maintain Vue Router Query Parameters Across Parent Components

In my application, I have a component named Foo, which serves as the template for a route called app/foo. Within this component, there are child components that also act as templates for routes such as app/foo/bar and app/foo/baz. I've implemented a ...

Utilizing a drop-down menu in AngularJS to dynamically change a URL and fetch images

Currently, I am in the process of creating a website using AngularJS that accesses images from reddit and showcases them based on various parameters such as number of votes and date posted. While this is not groundbreaking, my main goal is to enhance my sk ...

Error: TypeScript Knockout table failing to display data

I have a table that displays invoices, along with a nested table showing the individual checks associated with each invoice. I am using knockout and typescript to render these tables. Currently, I can successfully display the invoices but am facing difficu ...

Utilize Jquery to dynamically modify the content on a webpage

I am looking to use Tampermonkey in order to reverse the text on a specific website, like BBC News. I have already started working on a script that can replace certain text, but I am facing difficulty in accessing all the text present on the page efficient ...

Deciphering the method to retain added text

Imagine you have this code snippet: $('.button').click(function() { $('body').append("<p>Random Text</p>"); }); Whenever the .button is clicked, text is added to the body. How can we make sure that this text is saved a ...

Tips on creating a slow and gradual border animation that unfolds smoothly

I am looking to create an animation effect on a border, gradually revealing it like in this Codepen example. However, my specific requirements are: The previous line should not be removed, but rather shown along with the new border. The border color ...