比较两个包含多个值对的JavaScript数组

时间:2015-03-30 21:10:22

标签: javascript arrays

我有两个阵列,我试图与以下格式的数据进行比较:

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,& #34; 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] ); 
      } 
   }
}   

提前致谢!

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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语句