在java脚本中比较和过滤多维数组?

时间:2011-02-21 13:40:01

标签: javascript multidimensional-array filtering

我有两个多维数组。第一个包含大量这样的数据:

var dataarray = [ ["AX005A", "Dust / Gas", "1D / 2G", "21", "Ex II 3D IP67"],
["AX007A", "Dust / Gas", "3D / 3G", "22 / 2", "Ex II 3D T60"],
["AX008A", "Dust / Gas", "3D / 3G", "21", "Ex II 3D T60"],
["AX014A", "Dust", "3D", "22", "Ex II 3D T60"],
["AY042A", "Dust", "3D", "20", "Ex II 3D IP65 T65"],
["AY046A", "Dust", "3D", "21", "Ex II 3D T65"]];

第二个包含这样的搜索结果:

var searchterms = [["1","Dust / Gas"],["3","21"]];

现在我想要一个只包含数据的结果数组,其中dataarray与seterterms [n] [0]

给出的正确索引处的每个searchterms匹配

对于上面给出的seachterms,resultarray将是:

resultarray = [["AX005A", "Dust / Gas", "1D / 2G", "21", "Ex II 3D IP67"],
["AX008A", "Dust / Gas", "3D / 3G", "21", "Ex II 3D T60"]];

由于searchterms的数量并不总是相同,因此它必须是一个通用的解决方案,可以使用2个searchterms,就像使用4个或5个searchterms一样。

我尝试使用各种if条件嵌套“for loops”但我在某些时候迷失了:(

如果有人可以提供帮助,我会很棒。 我只能使用的框架是jquery(如果这有帮助的话)

2 个答案:

答案 0 :(得分:3)

第一个解决方案是:

function find(haystack, needles) {
    var results = [];
    for(var i = haystack.length; i--;) {
        var matches = true;
        var item = haystack[i];
        for(var j = needles.length; j--; ) {
            var needle = needles[j];
            if(needle[1] !== item[needle[0]]) {
                matches = false;
                break;
            }
        }
        if(matches) {
            results.push(item);
        }
    }
    return results;
}

DEMO我认为您的搜索字词必须为["3","21"],而不是["4","21"]

您可以重构代码并使用对象而不是数组(对于find函数不会改变那么多,但更容易创建)。例如。 searchterms可以是对象{0: "Dust / Gas", 3: "21"},它会将内部for循环更改为

for(var key in needles) {
   if(needles.hasOwnProperty(key)) {
       if(needles[key] !== item[key]) {
           matches = false;
           break;
       }
   }
}

答案 1 :(得分:0)

我不得不把我的代码放到,因为你的问题输入错误,我没有工作。 http://jsfiddle.net/cwZz7/3/在此处查看

var dataarray = [ ["AX005A", "Dust / Gas", "1D / 2G", "21", "Ex II 3D IP67"],
["AX007A", "Dust / Gas", "3D / 3G", "22 / 2", "Ex II 3D T60"],
["AX008A", "Dust / Gas", "3D / 3G", "21", "Ex II 3D T60"],
["AX014A", "Dust", "3D", "22", "Ex II 3D T60"],
["AY042A", "Dust", "3D", "20", "Ex II 3D IP65 T65"],
["AY046A", "Dust", "3D", "21", "Ex II 3D T65"]];

var searchterms = [["1","Dust / Gas"],["3","21"]];    
/*
resultarray = [["AX005A", "Dust / Gas", "1D / 2G", "21", "Ex II 3D IP67"],
["AX008A", "Dust / Gas", "3D / 3G", "21", "Ex II 3D T60"]];
*/


var resultArray = new Array();

for(i=0;i< dataarray.length; i++)
{
    var valid = true;
    for(j=0;j < searchterms.length;j++)
    {
          var index = parseInt(searchterms[j][0]);
          if(dataarray[i][index] != searchterms[j][1]){
                 valid = false;
                 break;
          }         

    }
    if(valid == true)
            resultArray.push(dataarray[i]);

}

// resultArray will have your result