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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With