Marek Has
Marek Has

Reputation: 177

Vue.js - how to sort and objects inside the array by particular property and render it with "v-for"

I have an array with a few objects inside. Each object contains a few properties.

I use vue.js v-for method to render it in the list.

But I cannot render it in the specific order of the given property. I use this function to sort it ascending:

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

It works fine with a simple array like [22, 1, 2, 3, 4, 5]. But it does not work for the objects like this:

      numbers2: [
      {
        name: 'Alan',
        age: 72
      }, 
      {
        name: 'Thomas',
        age: 32
      }, 
      {
        name: 'Thomas',
        age: 32
      }, 
      {
        name: 'Michal',
        age: 32
      },
    ]
  }

I want to sort them by the age in the ascending order.

At the end I want to render them inside the li for example only {{ age }} property.

Here is a snippet with my code: https://jsfiddle.net/marektchas/jyznx475/2/

Upvotes: 2

Views: 1436

Answers (1)

acdcjunior
acdcjunior

Reputation: 135762

Since you now have complex objects, sorting by the object directly won't work as you expect (the operator runs some implicit conversions resulting in NaN for every comparison).

You must sort by the specific property, in this case, age. So:

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

See updated fiddle.

Upvotes: 4

Related Questions