2

I'm trying to sort a list of items in VueJS 2 with slice().sort(), but it doesn't have any effect. In vuejs 1 there was a nice orderBy filter, but they removed this. My current setup is as followed:

<table>
        <thead>
          <tr>
            <th v-for="column in columns" v-on:click="sortBy(column)">{{ column }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="customer in customerslist">
            <td>{{ customer.firstname }}</td>
            <td>{{ customer.surname }}</td>
            <td>{{ customer.added }}</td>
            <td></td>
          </tr>
        </tbody>
      </table>

...

      sortBy(sortKey) {
        this.customerslist = this.customerslist.slice().sort(sortKey);
        console.log(sortKey);
        console.log(this.customerslist[0].firstname);
      }

It's a 2 dimensional array with customers. Each customers has a firstname, surname, and added field.

But this always returns the same firstname in console if I click the firstname column header (while this isn't the alphabetically correct one). How does sorting work, since I can't find the right documentation on it.

1 Answer 1

4

Your problem doesn't have anything to do with Vue. Array sorting in JavaScript just works differently than you expected. You can't pass a key to sort(); instead you have to implement your own compare function:

this.customerslist.sort((a, b) => a[sortKey].localeCompare(b[sortKey]));

Also sorting works in-place so it shouldn't be necessary to copy and reassign the array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.