screen_rotation
Copied to Clipboard
<html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <h3>Vue js sort array alphabetically</h3> <div id="app"> <button @click="toggleSortOrder">{{ sortOrderButtonText }}</button> <table> <tr> <th>S.no</th> <th>Developer_Name</th> </tr> <tr v-for="(item, index) in sortedItems"> <td>{{ index + 1 }}</td> <td>{{ item.name }}</td> </tr> </table><br> </div> <script type="module"> const app = new Vue({ el: "#app", data() { return { items: [ { id: 1, name: 'Andrew' }, { id: 2, name: 'CodeSmith' }, { id: 3, name: 'Softwize' }, { id: 4, name: 'DevHive' }, { id: 5, name: 'Matthew Taylor' }, { id: 6, name: 'ByteBuilders' }, { id: 7, name: 'Jennifer Lee' }, { id: 8, name: 'Robert Thompson' }, { id: 9, name: 'Christopher Davis' }, { id: 10, name: 'Laura Smith' }, { id: 11, name: 'William Johnson' }, { id: 12, name: 'Elizabeth Martinez' }, { id: 13, name: 'David Lee' }, { id: 14, name: 'Andrew' }, { id: 15, name: 'AlgoAllies' }, ], sortOrder: "asc" }; }, computed: { sortedItems() { let sortedArray = [...this.items]; sortedArray.sort((a, b) => { let comparison = 0; if (a.name < b.name) { comparison = -1; } else if (a.name > b.name) { comparison = 1; } return comparison; }); if (this.sortOrder === "desc") { sortedArray.reverse(); } return sortedArray; }, sortOrderButtonText() { return this.sortOrder === "asc" ? "Sort Descending" : "Sort Ascending"; } }, methods: { toggleSortOrder() { this.sortOrder = this.sortOrder === "asc" ? "desc" : "asc"; } } }); </script> <style scoped> /* Style the table */ table { border-collapse: collapse; width: 100%; } th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; } /* Style the header row */ th { background-color: #4CAF50; color: white; } /* Style the button */ button { background-color: #4CAF50; color: white; padding: 8px; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #3e8e41; } /* Alternate row color */ tr:nth-child(even) { background-color: #f2f2f2; } /* Style the container */ #app { margin: 20px; } </style> </body> </html>