2016-06-15 48 views
0

我需要檢查一個JavaScript數組,看看是否有重複的值。什麼是最簡單的方法來做到這一點?我只需要檢查值是否已經存在,如果不需要進入json數組。json數組檢查是否不需要在localstorage中插入?

function cek() { 
 
    resi_or_code = document.getElementById('code_or_resi').value; 
 
    resi = resi_or_code.split(','); 
 
    if($.trim(resi_or_code) != ''){ 
 
     location.href = base_url + 'resi/' + encodeURIComponent(resi_or_code); 
 
    
 
     } 
 
     if (localStorage.daftar_data){ 
 
      daftar_data = JSON.parse(localStorage.getItem('daftar_data')); 
 
      $("#riwayat").toggle(); 
 

 
     } 
 
     else { 
 
     daftar_data = []; 
 
     } 
 

 
    for (y in daftar_data){ 
 
     var q = daftar_data[y].resis; 
 
     for (x in resi){ 
 
     console.log(q); 
 
      if (q === resi[x]) 
 
      { 
 
      console.log('Value exist'); 
 

 
      }else{ 
 
      console.log('Value does not exist'); 
 
      daftar_data.push({'resis':resi[x]}); 
 
      localStorage.setItem('daftar_data', JSON.stringify(daftar_data)); 
 
      } 
 
     } 
 
    } 
 

 
    
 
}

+0

兩個不同的問題相同的代碼? http://stackoverflow.com/questions/37828082/remove-duplicate-input-value-using-javascript#37828082 – brk

回答

0

到目前爲止,最簡單的方法是簡單地排序您的陣列使用Array.sort()。這樣可以很好地發揮作用,並將重複檢查減少到一個簡單的for-loop,將每個值與其鄰居進行比較。

嘗試避免排序的解決方案几乎肯定會非常嚴重。

所以回顧一下,並顯示一些代碼:

daftar_data.sort(); 
for (var index = 0; index < daftar_data.length - 1; index++) 
{ 
    if (daftar_data[index] === daftar_data[index+1]) { 
    // Found a duplicate 
    } 
} 

如果對象的自然排序順序不爲你工作,提供一個功能排序功能,就像這樣:

daftar_data.sort(function(a, b) { 
    // return any value > 0 if a is greater, < 0 if b is greater 
    // and 0 if they are equal. 
}); 

請注意,在此表單中,您可以實際檢查比較函數中的重複項。

+0

不是數組而是對象 – Iswadi

+0

我看不到,因爲你沒有提交你的JSON。但實際上,您在第14行分配了一個空數組,並且還使用了push()。所以它看起來像一個數組。 –

+0

你的解決方案如何? – Iswadi

0

如果我理解你的問題和代碼的權利,你基本上有對象的數組,每個對象都有關鍵resis

如果是這樣的話,下面的代碼可能會幫助

var valueArray = ar.map(function(item) { 
    return item.resis; 
}) 

// To check for duplicate 
if(valueArray.indexOf(value) !== -1) { 
    // Duplicates 
} else { 
    // No duplicate 
} 

你的情況, ar將是daftar_data。 我真的不知道你的value是。是resi? 基本上,你應該嘗試用上面的代碼替換你的for循環。

+0

因此,localStorage已經有數據,我想比較localStorage中的數據與用戶輸入,如果用戶輸入現有dilocalstorage不會保存 – Iswadi

+0

編輯答案。 – Sanjay

+0

回答更多詳細信息 – Iswadi