Array Sort in Vue.js

How can I sort an array by name or gender before displaying it in a v-for loop? https://jsfiddle.net/rg50h7hx/

<div id="string"> <ul> <li v-for="array in arrays">{{ array.name }}</li> </ul> </div> 
 // Vue.js v. 2.1.8 var string = new Vue({ el: '#string', data: { arrays: [ { name: 'kano', sex: 'man' }, { name: 'striker', sex: 'man' }, { name: 'sonya', sex: 'woman' }, { name: 'sindell', sex: 'woman' }, { name: 'subzero', sex: 'man' } ] } }) 

Do I need to use "calculated" or something else?

+25
vuejs2
source share
5 answers

Yes, an easy way to do this is to create a computed property that can return sortedArray, for example:

 computed: { sortedArray: function() { function compare(a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; } return this.arrays.sort(compare); } } 

See a working demo .

You can find the sorting documentation here , which uses the compareFunction function.

compareFunction Defines a function that determines the sort order. If omitted, the array is sorted according to each character value of the code point of the Unicode character according to the string conversion of each element.

+41
source share

with es6 arrow functions:

 sortedArray(){ return this.arrays.sort((a, b) => a.name - b.name ); } 
+17
source share

HTML side

 <div id="string"> <ul> <li v-for="array in sortArrays(arrays)">{{ array.name }}</li> </ul> </div> 

Vue JS code || Using Lodash

 var string = new Vue({ el: '#string', data: { arrays: [ { name: 'kano', sex: 'man' }, { name: 'striker', sex: 'man' }, { name: 'sonya', sex: 'woman' }, { name: 'sindell', sex: 'woman' }, { name: 'subzero', sex: 'man' } ] }, methods: { sortArrays(arrays) { return _.orderBy(arrays, 'name', 'asc'); } } }) 
  • in the orderBy function, the first argument is an array, the second argument is the key (name / gender), the third argument is order (asc / desc)
+7
source share

Simple way; You can use computedArray instead of an array

 computed: { computedFonksiyon() { this.arrays.sort(function(x, y) { return y.name- x.name; }); return this.arrays; } } 
+1
source share

This works really cool:

 sortFunc: function (){ return this.arrays.slice().sort(function(a, b){ return (a.name > b.name) ? 1 : -1; }); } 

call a function from HTML:

 <div id="string"> <ul> <li v-for="array in sortFunc()">{{ array.name }}</li> </ul> </div> 
0
source share

All Articles