缩减数组以从左至右删除重复的matchId条目

问题描述 投票:0回答:2
当用户更新matchId的得分时,

pushing一个对象到数组中,我希望我的最终数组删除matchId的所有最旧的重复项,因此从索引0到结尾都在那里方式?

我有这个:

0: {matchId: "271691", homeTeamScore: "1", awayTeamScore: "1"}
1: {matchId: "271692", homeTeamScore: "1", awayTeamScore: "1"}
2: {matchId: "271700", homeTeamScore: "1", awayTeamScore: "1"}
3: {matchId: "271691", homeTeamScore: "6", awayTeamScore: "6"}
4: {matchId: "271691", homeTeamScore: "8", awayTeamScore: "8"}
5: {matchId: "271691", homeTeamScore: "8", awayTeamScore: "8"}
6: {matchId: "271691", homeTeamScore: "8", awayTeamScore: "0"}

我想要这样:

0: {matchId: "271692", homeTeamScore: "1", awayTeamScore: "1"}
1: {matchId: "271700", homeTeamScore: "1", awayTeamScore: "1"}
2: {matchId: "271691", homeTeamScore: "8", awayTeamScore: "0"}

我的代码:

saveResult(data: any, pushMatchId: any) {
    if (this.savedResults) {
      let cleanData = this.savedResults.map((item) => {
        return {
          matchId: item.matchId,
          homeTeamScore: item.homeTeamScore,
          awayTeamScore: item.homeTeamScore,
        };
      });
      data.map((item) => {
        cleanData.push(item);
      });
      this.db.collection("users").doc(this.user.uid).update({
        results: cleanData,
      });
    } else {
      this.db.collection("users").doc(this.user.uid).set({
        results: data,
      });
    }

  }
javascript typescript angularfire reduce
2个回答
0
投票

一个选项是创建一个Set以跟踪您之前看到的matchId字符串,反转数组,并根据是否已看到该元素对其进行过滤。

const input = [
  {matchId: "271691", homeTeamScore: "1", awayTeamScore: "1"},
  {matchId: "271692", homeTeamScore: "1", awayTeamScore: "1"},
  {matchId: "271700", homeTeamScore: "1", awayTeamScore: "1"},
  {matchId: "271691", homeTeamScore: "6", awayTeamScore: "6"},
  {matchId: "271691", homeTeamScore: "8", awayTeamScore: "8"},
  {matchId: "271691", homeTeamScore: "8", awayTeamScore: "8"},
  {matchId: "271691", homeTeamScore: "8", awayTeamScore: "0"}
];

const exists = new Set();

const unique = [...input].reverse().filter(({matchId}) => {
  if (!exists.has(matchId)) {
    exists.add(matchId);
    return true;
  }
  return false;
})

console.log(unique);

0
投票

删除重复项听起来像是在问题解决后就解决了。为什么不完全阻止添加重复项?

在添加到数组之前,请检查matchId是否已在数组中,如果将其过滤掉,则添加新数据。如果没有,请添加新数据

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.