[Vuejs]-Duplicate Keys in Vue v-for Loop When Table is Sorted

0👍

Phil’s comment provided the clue to this behaviour – in that the sort() function is working on the underlying data rather than a copy.

I have modified my template so that the v-for now loops over a computed array which can be sorted using the (slightly modified) function.

The sort function now uses slice() to create a copy of the underlying array:

computed: {
  sorted_lines() {
    return sort_string(lines, this.sort_column) // name of the column/filed to sort by
  }

The sort_string function now looks like this (with addition of slice()

sort_string(table, column) {
  console.log("sorting")
  //this.sort_toggle = -this.sort_toggle; // moved elsewhere

  return table.slice().sort((a, b) => { // slice() then sort()
  if (
    a[column].toString().toUpperCase() <
    b[column].toString().toUpperCase()
  ) {
    return -this.sort_toggle;
  }
  if (
    a[column].toString().toUpperCase() >
    b[column].toString().toUpperCase()
  ) {
    return this.sort_toggle;
  }
  return 0;
});
},

Leave a comment