Sorting and rendering objects within an array based on a specific property using Vue.js with the "v-for" directive

I have an array of objects with various properties. I am using the v-for method in vue.js to render them in a list.

However, I am facing issues trying to sort the objects based on a specific property. Currently, I am sorting them in ascending order using the following function:

    evenNumbers: function () {
      return this.numbers.sort(function (a, b) { return a - b });
    }

This works well for a simple array like [22, 1, 2, 3, 4, 5], but it fails for objects containing properties such as name and age.

      numbers2: [
      {
        name: 'Alan',
        age: 72
      }, 
      {
        name: 'Thomas',
        age: 32
      },
      // More similar objects here...
    ]
  }

I want to be able to sort these objects by age in ascending order and then render only the age property inside an li element.

You can view the code snippet here: https://jsfiddle.net/marektchas/jyznx475/2/

Answer №1

When dealing with complex objects, sorting directly by the object may not yield the expected results due to implicit conversions resulting in NaN values for comparisons.

To achieve the desired sorting, it is important to specify the property to sort by, such as age in this case. Therefore:

    evenNumbers2: function () {
      return this.numbers2.sort(function (a, b) { return a.age - b.age });
    }

For more details, refer to the updated fiddle.

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

Using Numpy's where() function with a two-dimensional array

I have a matrix with the following values data = np.array([[1,2,3,'foo'], [2,3,4,'bar'], [5,6,7,'hello'], [8,9,1,'bar']]) I am looking to identify the indices of the rows that contain the string 'bar' ...

Vue.js numerical input module

My approach involves utilizing Numeral.js: Vue.filter('formatNumber', function (value) { return numeral(value).format('0,0.[000]') }) Vue.component('input-number', { templa ...

Axios JWT fails to transmit

I am currently working on a project that has two layers - the back-end is developed using Spring Boot with security measures in place such as Sprint Security and JWT, while the front-end is built using Vue.js with Axios library for inter-layer communicatio ...

Encountering an unhandled runtime error in Next.js related to a CSS tag

I am encountering an error with the following line of CSS code: <div className={`${style.about__me-image}`}> How can I correctly apply Next.js CSS to the above line? The error message reads: Server Error ReferenceError: image is not defined Please ...

Eliminating the table header in the absence of any rows

I have successfully implemented a Bootstrap table in my React application, where users can add or delete rows by clicking on specific buttons. However, I want to hide the table header when there are no rows present in the table. Can anyone guide me on how ...

Troubleshooting a JavaScript Error in AngularJS Module

I created a Module called "app" with some helper functions in the file "scripts/apps.js": angular.module('app', ['ngResource']).run(function($scope){ $scope.UTIL = { setup_pod_variables: function (pods){...} ... }); Now, I want to ...

Receiving the most recent data in a protractor examination as a text string

My goal is to fetch an input value for a specific operation in protractor. I am attempting to make an ajax request using protractor and need to assign a unique value (referred to as groupCode) to a JSON object that will be sent to the server. Initially, I ...

Customize CSS based on user's device in Google Script Web App

Seeking Clarity: I have a straightforward project involving a Google Script / Web App, but I am struggling to find a way to load a specific CSS file based on the user's device. In other words, rather than focusing on responsive design, I need to loa ...

Navigating - Utilizing dot-notation to reach the top-level function in Express

If we want to use express in a basic javascript file, all we need to do is add the following two lines of code at the beginning (after installing it through npm): var foo = require('express'); var app = foo(); According to the express API guide ...

AngularJS: Assigning a value to an element

I am facing the challenge of automating an iframe using Selenium Webdriver and need to input a value into a text box. Here is the HTML code: <input class="ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-maxlength ng-touched" id="name" typ ...

Organize Your Data in AngularJS After Completing Calculations in the View

I am wondering about incorporating math calculations on a view and organizing the values in Angular. While I understand that these calculations can be done beforehand, I am curious if it can be achieved after the fact as well. Here is the link to my jsFidd ...

Transforming a data array into JSON format with the help of a property mapping technique

I am attempting to transform a 2d array into a JSON object using a key map. The key map is defined as var keys = ['id', 'title', 'customer.id', 'customer.name', 'customer.phone.home', 'customer.phone.m ...

Customize a div's background color with an Angular directive

Imagine having a div element: <div id="wrapper"> some text </div> How can you create an angular directive that changes the background based on user input? For instance, you might have tried: <div id="wrapper" color temperature="51"> ...

What is the reason for `React.renderToNodeStream` not pausing for the event loop?

Attempting to enhance React's renderToString and renderToStaticMarkup by accommodating the event loop for better server request handling, like so: const React = require('react'); const { renderToNodeStream } = require('react-dom/server& ...

Guidelines on launching an ionic 4 modal using routes

How can I open a modal using routes? I attempted the following approach, but it did not work as expected: ngOnInit() { this.launchModal(); } async launchModal() { const modal = await this.modalController.create({ component: AuthPasswordR ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Looking to construct dynamic checkboxes in Angular by parsing a JSON object retrieved through AJAX

I have a JSON document structured like the example below, and I am looking to generate checkboxes dynamically using Angular. let data = { "Name":[ { "tagId":4489,"name":"Name","label":"Employee Name" } ], "Service":[ { "tagId": ...

What strategies can I use to eliminate nested loops while constructing a navigation?

I am working with a JSON file that contains data for a navigation panel consisting of links. A brief snippet of the file is shown below: [ { "category": "Pages", "links": [ { "url": "#", "cap ...

Tips for resolving problems with vue-transitions not being activated or triggered by methods

Currently, I am engrossed in a study project centered around vue-cli. It may seem fairly straightforward at first glance, but I am eager to implement some of the new concepts I have been learning. Within my project, I have a header featuring two distinct ...

unable to extract variable from the page via query

Having trouble passing $id to the query in PHP I'm currently working on an inline edit script that requires data from a MySQL query obtained based on the URL parameter ?id=. Even though I am successfully retrieving and displaying the id using $_GET $ ...