2015-01-09 67 views
0

我想比較日期存儲在格式'YMD他'從一個數組希望刪除重複項和創建一個計數沿邊thr信號日期,我比較日期使用下面的代碼:比較日期和創建計數javascript

function compare(a, b){ 
      if(a.getDate() == b.getDate() && a.getMonth() == b.getMonth() && a.getFullYear() == b.getFullYear()){ 
       return true; 
      }else{ 
       return false; 
      }; 
     }; 

這是我如何通過他們的循環:

times.forEach(function(timeOne){ 
     times.forEach(function(timeTwo){ 
      if(compare(timeOne, timeTwo)){ 
       console.log("same"); 
      }else{ 
       console.log("different"); 
       count.push(timeOne); 
      }; 
     }); 
    }); 

當我做到這一點似乎也沒有工作,只是刪除第一個1619倍的值,它不推計數數組並導致我的瀏覽器崩潰。任何關於如何克服這個或更好的方式來實現我所需要的建議。我現在還不確定如何創建點數。

編輯---

下面是程序的剩餘代碼:

var results = <?php echo $results; ?>,                             
      times = [],                                   
      count = []; 
    results.forEach(function(result){                              
     times.push(new Date(result.time));                             
    }); 

我也想提一提的是,項目數組是近30,000項。所以我需要一種可以大幅減少處理時間的方法。

+0

這可能會幫助你,有很多方法來檢查重複項並創建一個新的唯一數組:http:// stackoverflow。com/questions/9229645/remove-duplicates-from-javascript-array,最重要的是你可以顯示你初始化count的位置? – Royalty

+0

@Royalty編輯添加,將檢查鏈接。 – hudsond7

回答

1

我會給點建議。也許他們會解決你的問題。

首先,可以減少你的代碼:

function compare(a, b){ 
    if(a.getDate() == b.getDate() && a.getMonth() == b.getMonth() && a.getFullYear() == b.getFullYear()){ 
     return true; 
    }else{ 
     return false; 
    }; 
}; 

function compare(a, b){ 
    return a.getDate() == b.getDate() && a.getMonth() == b.getMonth() && a.getFullYear() == b.getFullYear(); 
}; 

其次,你的循環是錯誤的。 內循環是循環變量i改爲j的:

for(var j = 0; j < times.length-1; i++){ 
     ... 
}; 

第三,既然你想刪除重複,你應該跳過的元素,我==Ĵ,因爲他們永遠是平等的。所以補充:

if(i == j) continue; 

到內部循環。

第四,你的方法是錯誤的。如果某個元素與其他元素不相同,則您將推送到count數組。這不保證沒有重複。看看,如果你有和[1,2,3,2]陣列,並嘗試使用你的算法刪除重複項,結果數組將如[1,1,1,1,2,2, 2,3,3,3,4,4,4,4]。這是因爲你正在按元素搜索模糊,但你應該通過數組來搜索它。你的算法必須保證你的數組中只有一種。一個適當的循環將是:

for(var i = 0; i < times.length; i++){ 
    if(times[i] == null || times[i] == undefined) continue; 
    if(!contains(count, times[i])){ 
     count.push(times[i]); 
    } 
} 

function contains(arr, elm){ 
    for(var i = 0; i < arr.length; i++){ 
     if(compare(elm, arr[i])) 
      return true; 
    } 
    return false; 
} 

計數數組現在應該只有一種每個日期,沒有愚蠢。

編輯後:

哇。 30000個條目。有30000個參賽作品的方法必須是另一個。試試這個解決方案,看看它是否能爲你解決,但我相信它不適合你的情況。

+0

非常豐富,工作和良好。在一個30,000+陣列上花費了幾毫秒。謝謝。 – hudsond7

+0

我有一個問題給你,我將如何去做這個多維度?例如爲每個日期添加一個頻率?我試圖改變代碼給運氣。 – hudsond7

+0

取決於您如何創建數據結構。 – Dalton

0
for(var i = 0; i < times.length-1; i++){ 
    for(var j = 0; j < times.length-1; i++){ 
     if((i!=j) && times[i] && times[j]){ 
      if(compare(times[i], times[j]) == true){ 
       console.log("same!!!"); 
      }else{ 
       console.log("not same!"); 
       count.push(times[i]); 
      }; 
     }; 
    }; 
}; 
+0

你能解釋一下你做了什麼,爲什麼這麼做? – hudsond7

+0

基本上添加一個支票(我!= j),因爲您正在比較您的數組項目與自身。 – imnancysun