0

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.

3
  • how do you know the recent sores? Commented Jan 27, 2023 at 10:53
  • Hi @Nina Scholz. They are the ones that are recorded last, so originally they are last in the array, I'm planning to reverse the array with reverse() and therefore get the last recorded items to be on top and display it that way. Commented Jan 27, 2023 at 10:58
  • Hi @Rohit Jindal, I will display the best results separately, than the recent results. There will be two components, one showing the best results of all time, and one showing the 5 most recent results. Commented Jan 27, 2023 at 11:02

1 Answer 1

1

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;
  }
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.