2015-03-30 33 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