【问题标题】:Sorting array coming from computed property, in a method also sorts the original array (that comes from the computed property)对来自计算属性的数组进行排序,在一种方法中还会对原始数组(来自计算属性)进行排序
【发布时间】:2023-01-27 18:50:21
【问题描述】:

我正在构建一个用于测验的 vue 应用程序,我想显示参加测验的人之前的所有结果。为此,我从后端获取结果,然后将它们传递给具有计算属性的“视图”组件:

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

我还想整理出最好的结果和最近的结果并分别显示,为此我有以下方法:

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

这是有效的,但是它以一种从最高到最低显示分数的方式对 allResults 数组进行排序,这就是我在 bestResults() 函数中所做的。这是一个问题,因为我想根据日期显示 recentResults,它应该在顶部显示最近的结果。

【问题讨论】:

  • 你怎么知道最近的疮?
  • 嗨@Nina Scholz。它们是最后记录的,所以最初它们是数组中的最后一个,我打算用 reverse() 反转数组,因此将最后记录的项目放在最上面并以这种方式显示。

标签: javascript arrays vue.js computed-properties


【解决方案1】:

那么,你先对bestResults()中的数组进行排序,然后在recentResults中使用排序后的数组。

作为一种解决方案,您可以创建一个具有相同元素的新数组并对其进行排序,这将保持原始数组不变:

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

【讨论】:

  • 这绝对有效@fjc,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-10-02
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多