Home > Software design >  Sorting array coming from computed property, in a method also sorts the original array (that comes f
Sorting array coming from computed property, in a method also sorts the original array (that comes f

Time:01-27

Im building a vue application for quizzes, I want to display the all the previous results of the person that has taken the quiz. For that I fetch the results from my backend and then pass them to the "view" component with a computed property:

   computed: {
    allResults() {
      return this.$store.state.allResults;
    },

I want to also sort out the best results, and the most recent results and display them separately, In order to do that I have the following methods:

 bestResults() {
    let orderedArray = this.allResults;

    orderedArray.sort((a, b) =>
      a.score < b.score ? 1 : a.score > b.score ? -1 : 0
    );
    let half = Math.round(orderedArray.length / 2);

    let bestResults = orderedArray.slice(0, half);
    return bestResults;
  },

 recentResults() {
    let recentResults = this.allResults.slice(0, 5);
    return recentResults;
  }

This works, however it sorts the allResults array in a way that shows the scores from highest to lowest, which is what I do in the bestResults() function. This is a problem since I want to display the recentResults based on date, which should show the most recent result on top.

CodePudding user response:

Well, you first sort the array in bestResults(), then use the sorted array in recentResults.

As a solution, you can create a new array with the same elements and sort that, which will leave the original array untouched:

 bestResults() {
    let orderedArray = [...this.allResults];

    orderedArray.sort((a, b) =>
      a.score < b.score ? 1 : a.score > b.score ? -1 : 0
    );
    let half = Math.round(orderedArray.length / 2);

    let bestResults = orderedArray.slice(0, half);
    return bestResults;
  },

 recentResults() {
    let recentResults = this.allResults.slice(0, 5);
    return recentResults;
  }
  • Related