[英]Comparing 2D-arrays - finding unique items
我有2個數組,需要識別array2中沒有出現在array1中的項。
在檢查唯一性時,只應比較第1,第2和第4個元素,第3個元素(庫存量)應排除在比較之外。
var array1 = [['892','NEW','2','blue'],
['675','USED','2','white'],
['943','NEW','2','green'],
['121','USED','2','yellow']];
var array2 = [['892','NEW','1','blue'],
['892','NEW','1','yellow'],
['121','USED','1','blue'],
['121','NEW','1','blue'],
['121','USED','1','yellow']];
結果應該是:
result = [
['892','NEW','1','yellow'],
['121','USED','1','blue'],
['121','NEW','1','blue']];
我已經嘗試重新處理針對類似問題發布的幾個解決方案,但是卻無法針對這種特定情況進行解決。
您可以通過檢查哈希表來獲取哈希表和從給定數組生成密鑰的函數,並過濾array2
。
function getKey(array) { return [0, 1, 3] .map(function (i) { return array[i]; }) .join('|'); } var array1 = [['892', 'NEW', '2', 'blue'], ['675', 'USED', '2', 'white'], ['943', 'NEW', '2', 'green'], ['121', 'USED', '2', 'yellow']], array2 = [['892', 'NEW', '1', 'blue'], ['892', 'NEW', '1', 'yellow'], ['121', 'USED', '1', 'blue'], ['121', 'NEW', '1', 'blue'], ['121', 'USED', '1', 'yellow']], hash = Object.create(null), result = []; array1.forEach(function (a) { hash[getKey(a)] = true; }); result = array2.filter(function (a) { return !hash[getKey(a)]; }); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
在js中它會像(更改為更短的代碼):
array2.filter(function(val){
return !array1.some(function(item){
return (val[0] == item[0] && val[1] == item[1] && val[3] == item[3]);
})
});
唯一的解決方案是將數組的每個元素與另一個數組的每個元素進行比較。 當你找到相同的東西時,你會退出循環並返回true。 如果沒有找到任何內容,只返回false並將元素添加到輸出數組中。 我希望這有幫助。
試試這個...你要跳過的索引只需在代碼下面的index []中給它
foreach(a中的var numberA){foreach(b中的var numberB){if(numberA == numberB){if(a.inex [3]){} else lblDate.Text + = numberA.ToString(); }}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.