Unable to sort array within a computed property in Vue.JS

Currently, I am working on enhancing my skills in Vue.js and have encountered an issue with sorting arrays in Vue.js. Despite using the sort(a-b) method for ascending order (least alphabet/value first), the array remains unchanged. Even with a function inside the computed property, I can't seem to make it work after hours of trying. Below is the code snippet:

<template>
  <div>
    <Navbar/>
    <div class="container p-4">
      <h1>{{ title }}</h1><br />
      <br>
      <Button/>
      <Table :people="sortedPeople"/>
    </div>
    <Modal @submit="submitPerson" />
  </div>
</template>
<script>
  import Navbar from './components/Navbar.vue'
  import Button from './components/Button'
  import Table from './components/Table.vue'
  import Modal from './components/Modal.vue'

  export default {
    name: 'App',
    data(){
      return {
        title: 'People',
        name:'Rename This',
        people: [
          {
            fname: 'Ab',
            lname: 'Zigzag'
          },
          {
            fname: 'Al',
            lname: 'Alabasta'
          }
        ],
      }
    },
    components: { Button, Navbar, Table, Modal },
    computed:{
      sortedPeople(){
        return this.people.sort((a, b) => a.lname - b.lname)
      }
    },
    methods: {
      submitPerson(person) {
        if(person.first_name && person.last_name) {
          this.people.push({ fname: person.first_name, lname: person.last_name })
        }
      }
    }
  }
</script>

Please find below the code snippet for my table component:

<template>
    <table class="table table-sm table-responsive table-hover">
        <thead>
            <tr>
                <th>Number</th>
                <th>Names</th>
                <th>Score</th>
            </tr>
        </thead>
        <tbody v-for="(person, i) in people">
            <tr>
                <td>{{  i+=1 }}</td>
                <td>{{ person.fname+" "+person.lname }}</td>
                <td>{{ Math.floor(Math.random() * 100) }}/100</td>
            </tr>
        </tbody>
    </table>
</template>
<script>
    export default {
        name: "Table",
        props: { people: Array },
    }
</script>

I would appreciate any guidance on the correct way to utilize a computed property. Thank you in advance.

Answer №1

If you want to arrange an array of strings in JavaScript, one way is to utilize the localeCompare method:

computed: {
  sortedNames() {
    return this.names.slice().sort((x, y) => x.lname.localeCompare(y.lname));
  }
}

When sorting strings using the sort function, subtracting x.lname - y.lname could lead to NaN.

It's important to use the slice() method here. Without it, the sort function would directly modify the original array instead of creating a new sorted array.

Answer №2

Employ the localeCompare() method in JavaScript to compare strings, for example:

sort((a, b) => a.lastName.localeCompare(b.lastName))

Answer №3

When writing your comparator function, it's important to carefully consider all conditions before sorting.

this.people.sort((a,b) => {
  if (a.lname < b.lname) return -1
  if (a.lname > b.lname) return 1
  return 0
});

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

Error (CODE5022) JavaScript detected in Internet Explorer 10

Here is the code that I wrote: AjxException.reportScriptError = function(ex) { if (AjxException.reportScriptErrors && AjxException.scriptErrorHandler && !(ex instanceof AjxException)) { AjxException.scriptErrorHandler(ex); ...

Engaging with the CSS content attribute

Below is a code snippet that inserts an image before the header tag. Is there a way to incorporate JavaScript or jQuery in order to execute certain actions when the inserted image is clicked? h1::before { content: url(smiley.gif); } The HTML code fo ...

Populate a pair of div elements using just one AJAX request

Currently, I am attempting to use the load() function to ajaxly load two separate divs, #follow-x and #follow-y, by clicking a button. The approach I have taken is as follows within the success function of my code snippet. However, this method does not see ...

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 ...

Alter appearance using various classes

I am seeking assistance in changing the font of text using classes. I have multiple texts with different classes and I want to be able to edit all the texts without adding another dropdown menu. I believe that the change needs to occur in a script. Pleas ...

Enabling or disabling select input based on the selected option in a previous select dropdown

My goal here is to customize a select input with 3 options: Sale, Rent, Wanted. Based on the selection, I want to display one of three other select inputs. For example, if "Sale" is chosen, show the property sale input and hide the others. However, when su ...

What is the best way to ensure webpacker compiled javascript only runs once the page has finished loading in a rails application

What is the best location to place window.onload for it to execute on every page within a Rails 6 application? ...

Retrieve the ID of the image element using Jquery from a collection of images within a div container

I'm encountering a simple issue that I can't seem to solve. I am working on a basic slider/gallery with the following functionalities: 1) "If button 1 is clicked, image one will appear." 2) "Clicking on button 2 will make IMAGE 1 slide left and I ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

Looking for a solution to split barcode data across two text fields

I am looking to enhance my data input process by utilizing a barcode scanner in conjunction with JQuery. The barcode scanner I have reads both the serial number and model name of each product, but currently displays them together in one text field. Is ther ...

Ensuring Unique CSS for Diverse Devices: A User-Agent Driven Approach

I am facing multiple challenges and working towards finding solutions. I have developed a webpage and now I want to redirect the link to the CSS file based on the user agent. `<script type="text/css" src="style.css"> </script>` However, inst ...

Remove the click event once the sorting process has been completed

I am currently working on a project that involves creating a list of sortable images using jquery sortable. Users can easily drag and drop the images for sorting purposes. Additionally, each image's parent anchor has a click event attached to open it ...

Tips for preserving textarea content upon clicking outside the area with the help of ajax

I am new to using the Froala editor and I am currently working on a feature where I need to save text in the textarea of the editor when the user clicks outside of it using Ajax. The ID of the content editor is #id_content. Here is a snippet of my form in ...

What is the trick to incorporating nested tabs within tabs?

My tabs are functional and working smoothly. To view the jsfiddle, click here - http://jsfiddle.net/K3WVG/ I am looking for a way to add nested tabs within the existing tabs. I would prefer a CSS/HTML solution, but a JavaScript/jQuery method is also acce ...

How can I maintain focus selection while replacing HTML with text in a contenteditable div without losing it?

When working with a div tag that needs to be editable, the goal is to prevent users from entering any HTML into the tag. However, despite efforts to restrict input, when users copy and paste content, it often includes unwanted tags. To address this issue, ...

What is the best way to group an array based on a dynamic key?

My goal is to group values in an array by a given ID. I've attempted a method for this, but it's not working for dynamic keys. Here is the current array: let employees = [{"employeeDetail": [{"empID": "XXYYZZ11"," ...

Is there a method to automatically create .stories.ts files in Angular Storybook?

I am seeking a way to automatically create a .stories.ts file within a component folder after executing the command ng g component my-component. The desired outcome should resemble this structure: my-component -my-component.component.html . ...

Having trouble getting my javascript integration to work in a Django template - any ideas on what could be causing

As a newcomer to Django, I'm working on creating a small webpage that displays a chart using Chart.js. My goal is to load the JavaScript file statically. To achieve this, I have set up a basic HTML file named data_table.html and included a "static" fo ...

PHP and MySQL collaborate for live countdowns in real-time

Looking for a code solution to implement a real-time countdown feature, similar to deal expiration timers on shopping websites. I have an expiry time stored in MySQL which needs to be displayed whenever the page is accessed. Additionally, it should calcul ...

Tips on customizing regex to selectively identify specific strings without capturing unrelated ones

Currently, I am working with this regex: /(?<=^|\/)(?:(?!\/)(?!.*\/))(.*?)[:-]v([\d.-]+)(?=\.|$)/ The goal is to extract the captured group from the following strings: rhmtc/openshift-velero-plugin-rhel8:v1.7.9-4 oc-mirror-plug ...