Arrange Bootstrap-Vue table in a custom order of days (mon, tue, wed) instead of the default

I'm working on a table that populates data from a database using Bootstrap-vue. The database includes a field labeled "day" which contains string values like "mon", "tue", "wed", and so on. I need the table to sort this column by day order rather than alphabetically. Is there a way to achieve this?

My experience with Vue and Bootstrap Vue is still limited. While I've successfully set up the table to fetch data from the database and display it as objects based on defined fields, I'm struggling with sorting.

Here is a simplified code snippet illustrating the issue:

HTML:

<div id='root'>
   <b-container fluid>
      <h1>Welcome</h1>
      <br/>
      <b-table
         show-empty
         stacked="md"
         :items="tableItems"
         :fields="fields"
         sort-by="day"
      >
      </b-table>
   </b-container>
</div>

Vue:

new Vue({
el: '#root',
data() {
   return {
      tableItems: [
         {name: 'Mark', age: '23', day:'wed'},
         {name: 'John', age: '21', day:'thu'},
         {name: 'Stephen', age: '24', day:'tue'},
         {name: 'Will', age: '31', day:'fri'},
         {name: 'Andrew', age: '27', day:'wed'},
         {name: 'James', age: '24', day:'mon'},
         {name: 'Shawn', age: '29', day:'tue'},
      ],
      fields: [
         { key: 'name', label: 'Name', sortable: true},
         { key: 'age', label: 'Age', sortable: true, class: 'text-center' },
         { key: 'day', label: 'Day', sortable: true},
      ],
      }
   }
});

At present, the code organizes the data in the day column alphabetically. However, my goal is to have it sorted by days of the week (e.g., "mon", "tue", "wed", etc).

Answer №1

If you want to implement your own custom sorting method, you can achieve this by integrating with the :sort-compare routine.

  <b-table
     show-empty
     stacked="md"
     :items="tableItems"
     :fields="fields"
     :sort-compare="sortingChanged"
  >

Next, create a dictionary to assign values to days of the week.

const days = {
  "sun": 0,
  "mon": 1,
  "tue": 2,
  "wed": 3,
  "thu": 4,
  "fri": 5,
  "sat": 6,
};

Lastly, handle the sorting logic in your methods section.

  methods: {
    sortingChanged(a, b, key) {
      let result = 0;
      if (key === 'day') {
          let day1 = a[key].toLowerCase();
          let day2 = b[key].toLowerCase();
          return days[day1] - days[day2];
      } 
      return false;
    }
  }

The use of Math.min/max is to limit the value between -1 and 1 as required by the sort-compare routine for correct functioning.

For a demonstration, check out this interactive codesandbox example. Further details on the sort-compare routine can be found in the documentation.

Credit goes to @TroyMorehouse for highlighting an improved methodology.

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

Show a separate div in a block format if the data field contains a value

<span>{{pstCtrl.doctorProfile.boardCertification ? === 'Yes' : $yes.display-block}}</span> <span class="yes">Yes</span> span.yes { display:none; } In my Angular.JS project, the code snippet above is demonstra ...

Ensure to first close the existing global connection before attempting to establish a new one in your Node.js Post WebApi application

Currently, I am in the process of creating a small post WebAPI using node.js to collect user data such as names and numbers. However, when I have an excessive number of users accessing this web API, I encounter the following error message: "node.js Global ...

When using Vue.js and Quasar to implement multiple filtering forms, an issue arises where the input value disappears

I am currently exploring how to implement multi-item filtering in Quasar, a framework of Vue. At the moment, I am utilizing input and checkbox elements. Everything seems to be functioning correctly, but there is an issue with the select item disappearing. ...

PHP query will execute even in the absence of clicking the button

I'm encountering an unusual issue. I've defined a query to insert two names into the database, and I've used Javascript(Jquery) to ensure it only runs when the create button is clicked. However, the script seems to be executing every time I ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

The functionality of the click event attached with the addEventListener is

I have a unique project where I am developing a user interface for a paper-rock-scissor game. To create the UI, I included four buttons: "Start game," "rock," "paper," and "scissor." Initially, I wrote separate code for each button, which worked perfectly ...

What is the best way to cycle through a JSON array of objects using JavaScript and jQuery?

Currently, my focus is on understanding JavaScript and JSON objects along with arrays. One of the tasks assigned to me involves iterating through the following array: {"6784": {"OD": [ { "od_id":"587641", ...

Troubleshooting issue: Django and Javascript - Why is my dependent dropdown feature not

I am new to using a combination of Javascript and Django. Below is the script I have written: <script> $(document).ready(function() { $("#source").change(function() { var el = $(this); var reg = ...

Running a child process in the browser using Node.js with the help of browserify

Utilizing browserify to enable node.js functionality in the browser, I am attempting to run a child process in my index.js file: var exec = require('child_process').exec; //Checking the installed node version var ls = exec('node -v', f ...

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...

Accessing composable variables in Vue 3 without having to redefine refs from within a function

Currently, I am implementing a parent companyList component along with a reusable Table component and an useFetch composable in vue 3.2. Prior to integrating the Table component, my code looked like this: companyList <script setup> import { com ...

incorporating my unique typographic styles into the MUI framework

I'm currently working on customizing the typography for my TypeScript Next.js project. Unfortunately, I am facing difficulties in configuring my code properly, which is causing it to not work as expected. Can someone kindly provide assistance or guida ...

Swiper: What methods can be used to classify the nature of an event?

Currently, I am utilizing Swiper for React in my project. I find myself in need of implementing a different effect when the user swipes versus using buttons to switch between active slides. Upon examining the swipe object for pertinent details regarding ...

Verify the pop-up browser window that appears when the page begins to reload using Cucumber

After completing one scenario, the page automatically refreshes. A JavaScript modal is displayed on the website asking the user "Are you sure you want to leave the page?" I need to confirm that modal, but every time I try to create a step for it, I encount ...

Concise way to add or insert an element into an array, at a specific property of an object

I am working with an object of the ObjectOfArrays type: type ObjectOfArrays = { [id: string]: Array<string> }; Throughout my code, I need to add strings to the correct array based on the id. Currently, I am using the following approach: if (id i ...

Guide on Adding a Map to a List in JavaScript

Currently, I am trying to extract data from a form and add it as a map to my list. However, an error message is displayed: Cannot read property 'url' of undefined express = require("express"); app = express(); var bodyParser = require("body- ...

Vue JS: When Computed Properties Fail to Trigger

I am currently using Vue.js and have implemented a computed property stored within my vuex. The issue I am facing is that when I add an item to the array, the watcher does not trigger. However, upon logging the item, it is indeed present. computed:{ ...

How can I use JavaScript to disable a table row and then save the selected option in a MySQL database?

I have a PHP snippet that dynamically displays table rows. Each row contains a radio button with "Yes" and "No" options. I have implemented a JS function where, upon choosing an option, a pop-up box is displayed. If the user selects the "Yes" option in t ...

Mantine UI: Elevate Your Component Library Experience

I am in the process of creating a Component library for internal company projects, which will be packaged as an npm package. To kick things off, I am starting with Mantine and plan to incorporate customization using tailwind CSS. As a test, I have created ...

When utilizing *NgIf, the button will be shown without the accompanying text being displayed

When trying to display either a confirm or cancel button based on a boolean set in my component.ts, I implemented the following code in my HTML: <mat-dialog-actions class="dialog-actions"> <button class="cancel-btn" ...