2015-03-30 36 views
-1

我有兩個數組我想在下面的格式數據來比較兩個JavaScript數組:比較包含多個值對

var order = [[1,"121"], [2,"111"], [2,"321"], [3,"232"], [3,"213"], [4,"211"]], 
userBuilt = [[4,"111"], [1,"131"], [3,"321"], [3,"232"], [3,"211"], [3,"213"], [1, "X1X"]]; 

var exactMatches=[]; 
var incorrect=[]; 

我想要把含有字符串匹配到一個陣列稱爲雙exactMatches = []以及userBuilt數組中完全唯一的項,例如[1,「X1X」]和[1,「131」]到名爲incorrect = []的另一個數組。下面的代碼適用於推送匹配,但我無法弄清楚如何將唯一對推送到不正確的= []數組。

for (var i = 0; i < order.length; i++) { 
    for (var e = 0; e < userBuilt.length; e++) { 
     if(order[i][1] === userBuilt[e][1]){ 
     exactMatches.push(userBuilt[i]); 
     } 
    } 
} 

在此先感謝!

+0

你會認爲在你的例子中'[3,「321」]'是完全唯一的還是隻有「部分唯一的」 - 沒有結果數組? – Bergi 2015-03-30 21:33:27

+0

@Bergi,那隻會是部分獨特的。 [3,「321」]會被推送到exactMatches。基本上,如果字符串部分的順序和userBuilt,那麼他們會被推送到exactMatches。如果沒有,那麼他們會去不正確的數組。 – 2015-03-30 22:18:17

+0

不知道爲什麼我得到了一個投票,這是一個合法的問題,但它很酷,我能夠讓我的功能工作。 – 2015-03-31 16:03:35

回答

1

我們不知道如果一個特定的元素有一個匹配,直到交叉循環完全完成。因此,如果以後發現,請跟蹤不匹配的索引並從跟蹤數組中取消索引。

找到後我們可以立即將匹配推送到數組中。

var order = [[1,"121"], [2,"111"], [2,"321"], [3,"232"], [3,"213"], [4,"211"]], 
    userBuilt = [[4,"111"], [1,"131"], [3,"321"], [3,"232"], [3,"211"], [3,"213"], [1, "X1X"]] 

var exactMatches=[] 
var incorrect=[] // keeping track of indexes so need two tracking arrays 
    incorrect['o'] = [] 
    incorrect['u'] = [] 

for (var i = 0; i < order.length; i++) { 
    for (var e = 0; e < userBuilt.length; e++) { 
     if (order[i][1] === userBuilt[e][1]) { // comparing second element only 
      exactMatches.push(userBuilt[e]); 
      incorrect['o'][i] = null; // remove from "no match" list 
      incorrect['u'][e] = null; // remove from "no match" list 
     } 
     else { // add to "no match" list 
      if (incorrect['o'][i] !== null) { incorrect['o'][i] = i; } 
      if (incorrect['u'][e] !== null) { incorrect['u'][e] = e; } 
     } 
    } 
} 
console.log(incorrect) 
console.log(exactMatches) 

exactMatches包含匹配項。

[[4, "111"], [3, "231"], [3, "232"], [3, "213"], [3, "211"]] 

incorrect包含指標不匹配的元素

[0, null, null, null, null, null] // order array 
[null, 1, null, null, null, null, 6] // userBuilt array 

JSFiddle

在你的榜樣你只比較子陣列的串部分。第一個數字被忽視。如果你想要兩個元素完全匹配,那麼只需在條件中包含order[i][0] === userBuilt[e][0]

+0

感謝您的回答!我不認爲通過跟蹤非匹配索引來採取這種方法。我能夠根據需要獲得功能。再次感謝! – 2015-03-31 16:02:30

0
for (var i = 0; i < order.length; i++) { 
for (var e = 0; e < userBuilt.length; e++) { 
    if(order[i][1] === userBuilt[e][1]){ 
     exactMatches.push(userBuilt[i]); 
    } else { 
     incorrect.push(userBuilt[i]); 
    } 
} 
} 

,如果它不exactMatches去,然後它不正確的,現在看來,這樣再加上一點不正確的數組中放入else語句

+0

如果在循環中稍後出現匹配,該怎麼辦? – bloodyKnuckles 2015-03-30 22:12:28

+0

我試圖做到上述,但不幸的是它不工作。下面的血腥Knuckles答案真的幫了我。 – 2015-03-31 16:00:46