【问题标题】:Using push() method and indexOf() method to remove/check duplicate dates from an array in AngularJS1使用 push() 方法和 indexOf() 方法从 AngularJS1 中的数组中删除/检查重复的日期
【发布时间】:2021-01-22 17:17:59
【问题描述】:

我能够提取 EPOCH 日期并将它们成功转换为字符串,但是我之前编写的代码没有检查或删除重复项。有人知道我可以添加什么吗?在这种情况下,时间戳是我从实时数据中提取的 EPOCH 日期! ANGULARJS1

【问题讨论】:

    标签: javascript angularjs duplicates indexof epoch


    【解决方案1】:
    var dateMap = {};
    for (i = 0; i < dbData.length; i++) {
      let tmp_date_str = "";
      let tmp_date = new Date(dbData[i].TIMESTAMP);
    
      tmp_date_str += tmp_date.getFullYear();
      tmp_date_str += "-";
    
      if ((tmp_date.getMonth()+1) < 10) {
          tmp_date_str += "0";
      }
    
      tmp_date_str += (tmp_date.getMonth()+1);
      tmp_date_str += "-";
    
      if (tmp_date.getDate() < 10) {
          tmp_date_str += "0";
      }
      tmp_date_str += tmp_date.getDate();
    
        // make it a map, and if value for this string already exists, do nothing
      if (!dateMap[tmp_date_str]) {
        dateMap[tmp_date_str] = true;
      }
    }
    

    如果您需要将日期作为数组获取,只需这样做

      var dates = Object.keys(dateMap)
    

    【讨论】:

      【解决方案2】:

      您可以使用set 消除重复:

      const mySet= new Set(["one", "two", "three", "one"]);
      
      mySet.has("one") // true            
      mySet.size === 3); // true
      

      Set 构造函数可以接受一个数组 初始化集合的项目。

      【讨论】:

        【解决方案3】:

        要检查和删除重复项,您可以使用angular.equals

        var newArray = [];
                    angular.forEach($scope.dates, function(value, key) {
                        var exists = false;
        
                        angular.forEach(newArray, function(val2, key) {
                        if(angular.equals(value.date, val2.date)){ exists = true }; 
                        });
        
                        if(exists == false && value.dates != "") { newArray.push(value); }
                    });
        
                    $scope.dates = newArray;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-07-17
          • 1970-01-01
          • 2010-12-04
          • 1970-01-01
          • 2015-08-08
          • 2013-03-22
          • 1970-01-01
          相关资源
          最近更新 更多