JS數組對象去重同時判斷兩個屬性是否相同

參考:https://blog.csdn.net/m0_58849641/article/details/124750983?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_baidulandingword~default-1-124750983-blog-125990334.pc_relevant_3mothn_strategy_and_data_recovery&spm=1001.2101.3001.4242.2&utm_relevant_index=4

  • 判斷如下的對象數組中某兩個屬性是否有重複記錄:
[{productGroup: 'WB', incubationTimeAdjustMonth: '1月'}
{productGroup: 'WB', incubationTimeAdjustMonth: '2月'}
{productGroup: 'WB', incubationTimeAdjustMonth: '3月'}
{productGroup: 'WB', incubationTimeAdjustMonth: '4月'}
{productGroup: 'CSB', incubationTimeAdjustMonth: '1月'}
{productGroup: 'CSB', incubationTimeAdjustMonth: '2月'}
{productGroup: 'CSB', incubationTimeAdjustMonth: '3月'}
{productGroup: 'CSB', incubationTimeAdjustMonth: '4月'}
{productGroup: 'ICB', incubationTimeAdjustMonth: '1月'}
{productGroup: 'ICB', incubationTimeAdjustMonth: '2月'}
{productGroup: 'ICB', incubationTimeAdjustMonth: '3月'}
{productGroup: 'ICB', incubationTimeAdjustMonth: '4月'}
{productGroup: 'ZNB', incubationTimeAdjustMonth: '1月'}
{productGroup: 'ZNB', incubationTimeAdjustMonth: '2月'}
{productGroup: 'ZNB', incubationTimeAdjustMonth: '3月'}
{productGroup: 'ZNB', incubationTimeAdjustMonth: '4月'}
{productGroup: 'WB', incubationTimeAdjustMonth: '4月'}
{productGroup: 'WB', incubationTimeAdjustMonth: '5月'}
{productGroup: 'WB', incubationTimeAdjustMonth: '6月'}
{productGroup: 'CSB', incubationTimeAdjustMonth: '5月'}
{productGroup: 'CSB', incubationTimeAdjustMonth: '6月'}]

 const newArr = this.f_CompareData(checkPlanSetIncubationAll);//去除重複記錄並得到一個新數組
 // 比較新的數組與原來的數組長度是否一致,不一致就說明有重複記錄
 if(newArr.length!=checkPlanSetIncubationAll.length)
 {
      //有重複記錄
 }
// 對象數組去重
    f_CompareData(arr)
    {
      const cache =[];
      for(const t of arr)
      {
        // 檢查是否存在
        if(cache.find(c=>c.productGroup == t.productGroup&& c.incubationTimeAdjustMonth==t.incubationTimeAdjustMonth))
        {
          continue;
        }
        cache.push(t);        
      }
      return cache;
    }
  • 注意這種方式只能判斷對象數組中某個屬性值是否有重複:
  // 判斷數組中有無重複記錄
  // const newArr = checkPlanSetIncubationAll.map(item =>item.productGroup&&item.incubationTimeAdjustMonth);//好像只能使用一個屬性,這裏兩個只有後面的生效了,這裏只得到了一個屬性值的新數組
  // const arrSet = new Set(newArr);//數組去重
  // if(arrSet.size !== newArr.length){
  //     flag.code=3;
  //     flag.message='同一個產品分組和同一個月份不能重複,請檢查';
  // }
  • 例子:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章