2

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/

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But how to render now inside the <li> for example only {{ age }} property?
All you need to do is use the dot notation in the template as well: <li v-for="n in evenNumbers2">{{ n.name }}'s age is {{ n.age }}!</li> see fiddle: jsfiddle.net/acdcjunior/5knh47yg/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.