typescript 如何获取Angular 中唯一的最新数据

bpsygsoo  于 2023-06-24  发布在  TypeScript
关注(0)|答案(3)|浏览(99)

我在数组arr中有这样的原始数据

[
{Id:1,
Date:20/06/2023,
ProdId:1
},
{Id:2,
Date:21/06/2023,
ProdId:1
},
{Id:3,
Date:21/06/2023,
ProdId:2
},
{Id:4,
Date:23/06/2023,
ProdId:2
},
{Id:5,
Date:20/06/2023,
ProdId:3
}
]

我想要的项目与独特的prodIds和它应该是最新的。我应该得到下面的数据

[
{Id:2,
Date:21/06/2023,
ProdId:1
},
{Id:4,
Date:23/06/2023,
ProdId:2
},
{Id:5,
Date:20/06/2023,
ProdId:3
}
]

我需要做什么?先谢谢你了!!

xwbd5t1u

xwbd5t1u1#

我相信可能有一个更简单的方法,但这对我来说很有效:

this.customers.sort((a, b) =>
      new Date(b.Date) > new Date(a.Date) ? 1 : -1
    );
    var uniqueCustomers = this.customers.filter((value, index, array) =>
      array.findIndex((c) => c.ProdId === value.ProdId) === index
    );
    console.log(JSON.stringify(uniqueCustomers));

此代码首先按日期排序。然后根据ProdId筛选唯一值。

lqfhib0f

lqfhib0f2#

const myArray = [
  {Id:1,
  Date:20/06/2023,
  ProdId:1
  },
  {Id:2,
  Date:21/06/2023,
  ProdId:1
  },
  {Id:3,
  Date:21/06/2023,
  ProdId:2
  },
  {Id:4,
  Date:23/06/2023,
  ProdId:2
  },
  {Id:5,
  Date:20/06/2023,
  ProdId:3
  }
];

诡计:

const modifiedArray = myArray.filter((item, idx, array) =>
          array.findLastIndex((c) => c.ProdId === item.ProdId) === idx
    );
lp0sw83n

lp0sw83n3#

function filterByProId(ProId: number){

    const filtered = myArray.filter((e:any) => e.ProId==ProId); //filter array by ProId
    var latest = filtered[0]; // get first item
    filtered.forEach(function(item){
       //get item with date greater than previous
       latest = (new Date(item.Date) > new Date(latest.Date)) ? item : latest; 
    })
}

使用函数filterByProId:

function gettill(end: number, start: number = 0){
    finalArray: any[] = [];
    for (let i = start; i < end; i++) {
        // push latest item with ProId = i to the final array
        finalArray.push(filterByProId(i)); 
    }
    return finalArray; //the filtered array returned
}

相关问题