Arranging Vue numbers

Vue data contains:

data: {
          offices: requestData,
          selectedFloors: [
            "3",
            "4",
            "5",
            "10",
            "11",
            "12",
          ],
          minJobAngle: 0,
          maxJobAngle: 80,
          minAreaAngle: 0,
          maxAreaAngle: 900
        }

The challenge is to filter table rows using the selected floors. Despite successful filtering, the selected floors are not in the desired order which should be 3, 4, 5, 10, 11, 12.

In the methods section, there is a function called:

getFilteredOffices() {
            const areaMin = this.sliderAreaMin;
            const areaMax = this.sliderAreaMax;
            const jobsMin = this.sliderJobMin;
            const jobsMax = this.sliderJobMax;
            const floors = this.selectedFloors;
            return this.offices.filter(function (item) {

              if (item.acf.suurus < areaMin || item.acf.suurus > areaMax) {
                return false;
              }
              if (item.acf.tookohad < jobsMin || item.acf.tookohad > jobsMax) {
                return false;
              }
              if (!floors.includes(item.acf.floor)) {
                return false;
              }
              return true;
            });
          }

In the computed section:

    getAvailableFloors() {
            const set = new Set();

            const sorted = this.offices.sort((a, b) => {
              if (a.acf.floor > b.acf.floor) {
                return 1;
              }
              if (a.acf.floor < b.acf.floor) {
                return -1;
              }
              return 0;
            });

            sorted.forEach((office) => {
              set.add(office.acf.floor);
            });

            return set;
          },

The HTML code being used:

<label :class="['checkbox-label floor' + item]" v-for="item in this.getAvailableFloors">
   <input type="checkbox" name="floor" :value="item" v-model="selectedFloors"> @{{ item }}
   <span class="checkmark"></span>
</label>

Is anything missing here? How can we display these floors as 3, 4, 5, 10, 11, 12?

Answer №1

It seems like you're comparing strings instead of numbers in your code. Strings like 10, 11, and 12 will be considered lower than 2 or 3. Make sure to use parseInt to convert the string values before performing comparisons.

getAvailableFloors() {
  const set = new Set();

  const sorted = this.offices.sort((a, b) => {
    if (parseInt(a.acf.floor) > parseInt(b.acf.floor)) {
      return 1;
    }
    if (parseInt(a.acf.floor) < parseInt(b.acf.floor)) {
      return -1;
    }
    return 0;
  });

  sorted.forEach((office) => {
    set.add(office.acf.floor);
  });

  return set;
},

Answer №2

To ensure accurate comparisons between floors, it is necessary to convert them to numbers using Number('3'), for instance. This will prevent the comparison from being based on strings.

Comparing strings can result in alphabetical sorting (lexicographic ordering), where, for example, 10 < 2.

Take a look at the corrected sort function below:

 const sorted = this.offices.sort((a, b) => {
      const floorA = Number(a.acf.floor);
      const floorB = Number(b.acf.floor);
          
      if (floorA > floorB) {
           return 1;
      }
      
      if (floorA < floorB) {
          return -1;
      }

      return 0;
 });

For more information on type casting, visit: https://developer.mozilla.org/en-US/docs/Glossary/Type_Conversion

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

How Should One Properly Describe an Object with Multiple Dimensions?

PHP features multidimensional arrays, meaning an array that contains multiple arrays within it. When working with JavaScript, how does one refer to an object that holds multiple objects? Is it called a multidimensional object or is there a different termi ...

Unique trigger for clicking events with customizable widgets in JQuery

I'm in the process of developing a jquery widget that functions similarly to a menu bar, featuring two buttons - ButtonOne and ButtonTwo. With my HTML code and associated styles in place, I've been focusing on creating a "hello world" widget. / ...

If I dared to eliminate the emphasized line, this code would completely fall apart

<!DOCTYPE html> <html> <head> </head> <body> <h1 id="message-el">Ready to play?</h1> <p id="cards-el"></p> <p id="sum-el"></p> <butto ...

Iterating over an array while postponing a function

My goal is to create a continuous loop through an array of number values. These values will be used as delay parameters in a setInterval function, triggering another function each time. Here's what I've come up with: HTML: <p>On</p> ...

Count in JavaScript that picks up where it left off

I'm working on setting up a countdown timer that runs for 24 hours, showing the days, hours, minutes, and seconds. The challenge I'm facing is how to save the progress of the countdown. Essentially, I want it to resume from where it left off for ...

Is it possible to simultaneously run multiple functions with event listeners on a canvas?

I'm attempting to create a canvas function that displays the real-time mouse cursor location within the canvas and, upon clicking, should draw a circle. I came across this code snippet that reveals the x and y coordinates of the mouse: document.addEve ...

JavaScript queries in Selenium WebDriver

Lately, I have been using the selenium webdriver (nodejs module) along with mocha for writing automation tests, and encountered a few challenges along the way. Issue with Scrolling driver.findElement() seems to return false as it is unable to find the e ...

The JSON syntax contains an unexpected token

I am encountering an issue with a JavaScript variable named "text" that contains the following value: text={"text":"@RT #Olle_Carly Nuevas filtraciones del iPhone 6: así sería comparado con el Samsung Galaxy S5 y el iPhone 5S: Des... http://t.co/eRuXLS6 ...

AJAX Form Submission for CommentingAJAX allows for seamless form submission

Currently facing an issue with a form submission that is not displaying comments without refreshing the page. When the submit button is clicked, it redirects to the top of the page without executing any actions - no insertion into the database and subseque ...

Transferring multiple data between PHP and JavaScript

Here is the code I am using for the on change event: <script> $('.BIR').change(function() { var id = $(this).val(); //get the current value's option $.ajax({ type:'POST', dataType: "json", ...

Understanding the scope of variables in HTML files, JavaScript files, and PHP files when echoing statements

Is there a way to define a global javascript variable that can be accessed from multiple places within an HTML page? I need the variable to be accessible in three specific locations: Within the code of the HTML page favorites.php. Inside a separate javas ...

Trying to modify the chosen option while filtering an ajax source using select2?

I am currently integrating the select2 library within a Bootstrap 4 modal in the following manner: <div class="form-group" id="fg-jbInd"> <label for="jbIndustry" class="control-label"gt;Industry * <sele ...

What is the best way to isolate the elements from the specified dictionary that contain valid data?

I need to extract only the data for Flipkart from this array and create a new array containing just that information. json = [ { "amazon": [] }, { "flipkart": { "product_store": "Flipkart", ...

Extract the content inside an HTML <a> tag with a specified class and auto-populate it into a different text area

I found an HTML tag that is being generated by a WordPress plugin and it contains a random link. My goal is to automatically retrieve this generated link and place it in a textarea within a contact form. The generated code with the link (cannot be modifie ...

What is the best way to send multiple input box values to a function set in the controller?

I am attempting to send the values of two input boxes to a single controller function. <div class="container" ng-controller="MainCtrl"> <div class="row"> <div class="col-lg-6"> <input type="text" ...

Verify the occurrence of a search result and if it appears more than once, only show it once using JavaScript

Hello all. Currently, I am developing an online users script using NodeJS and SocketIO. The functionality works fine, however, I am encountering an issue where if a user connects from multiple browsers, windows, or devices, it displays duplicate results li ...

How can you alter a property within an array of records retrieved from a Mongoose query?

const images = await tbl .find({ creator_id: req.user._id, }) .select({ creator_id: 0, }) .exec() .then((images) => images.forEach((image) => { image.file_name = process.env.IMAGE_ ...

Trouble rendering Bootstrap dropdown in Vue2 component

I am experiencing a peculiar issue with my Vue child component, which is responsible for displaying a bootstrap modal and includes several fields, including one that should show a dropdown selection. Strangely, the dropdown button fails to activate, result ...

Utilizing ReactJs to Generate a Random Number for Visualization in a Material UI Progress Bar

I am looking to generate a random number for my test functionality in order to display it within a Material UI Progress bar. I have successfully implemented this piece of JavaScript code on JSFiddle, but now I want to integrate it into my React application ...

Swapping the non-DOM element text with another content

Currently facing an issue in my project where I need to replace plain text inside a contenteditable element without being enclosed in a DOM element. Here, I'm extracting the textNode using window.getSelection(); and looking to perform a text replaceme ...