Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array in Vue.js

Tags:

vuejs2

How can I sort an array by name or sex 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 have to use a "computed", or whatever?

like image 373
user3798618 Avatar asked Mar 19 '17 06:03

user3798618


People also ask

How do I sort a list in Vue?

The Grid component has support to sort data bound columns in ascending or descending order. This can be achieved by setting allowSorting property as true. To dynamically sort a particular column, click on its column header.

How do you sort elements in an array in JS?

The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.

How do I sort an array in bash?

If you want to handle embedded newlines, you can roll your own readarray. For example: sorted=(); while read -d $'\0' elem; do sorted[${#sorted[@]}]=$elem; done < <(printf '%s\0' "${array[@]}" | sort -z) . This also works in you are using bash v3 instead of bash v4, because readarray isn't available in bash v3.


1 Answers

Yes, an easy way to do this can be create a computed property which can return the sortedArray, like following:

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

You can find the documentation of sort here which takes a compareFunction.

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

like image 85
Saurabh Avatar answered Oct 14 '22 07:10

Saurabh