baeckerman83
6 months ago
64
3
Vue

Sort Array -> Why does this work?

Posted 6 months ago by baeckerman83

Hi! I want to sort a multidimensional array. This works fine in my component. But I don't know why. Because I dont asign the sorted array to this.myarr but in the browser the table is sorted after I click on the table header.

<template>
    <div>
        <table class="table">
            <thead>
                <tr>
                <th scope="col"></th>
                <th scope="col" @click="handleSortClick(1)">1</th>
                <th scope="col" @click="handleSortClick(2)">X</th>
                <th scope="col" @click="handleSortClick(3)">2</th>
                </tr>
            </thead>
            <tbody>
            <tr v-for="item in myarr">
                <th scope="row">{{item[0]}}</th>
                <td :class="{ 'table-success': item[1]==getMinOffArr(myarr,1), 'table-danger': item[1]==getMaxOffArr(myarr,1) }">{{item[1]}}</td>
                <td :class="{ 'table-success': item[2]==getMinOffArr(myarr,2), 'table-danger': item[2]==getMaxOffArr(myarr,2) }">{{item[2]}}</td>
                <td :class="{ 'table-success': item[3]==getMinOffArr(myarr,3), 'table-danger': item[3]==getMaxOffArr(myarr,3) }">{{item[3]}}</td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    function sortMultiArray(arr, idx){
        arr = arr.sort(function(a,b) {
            return a[idx] - b[idx];
        });
        return arr.reverse();
    }

    export default {
        props: ['myarr'],
        methods: {
            handleSortClick: function(idx) {
                sortMultiArray(this.myarr, idx);
            }
        }
    }
</script>

Please sign in or create an account to participate in this conversation.