6

我有一个像这样的多维 javascript 数组。

[
["9", "16", "19", "24", "29", "38"],
["9", "15", "19", "24", "29", "38"],
["10", "16", "19", "24", "29", "38"],
["9", "16", "17", "19", "24", "29", "39"],
["10", "16", "17", "19", "24", "29", "39"],
["9", "15", "21", "24", "29", "38"]

.......
.......
]

确切地说是40左右

并且我有另一个名为 check 的数组,其中包含以下值

 [9,10] //This is of size two for example,it may contain any number of elements BUT it only contains elements(digits) from the multidimensional array above

我想要的是我需要基于检查数组元素使多维数组唯一

1.Example if check array is [15] then多维数组将是

[
    ["9", "15", "19", "24", "29", "38"],
   //All the results which contain 15

]

2.Example if check array is [15,21] then多维数组将是

[
    ["9", "15", "21", "24", "29", "38"]
    //simply containing 15 AND 21.Please note previous example has only 15 in it not 21
    //I need an AND not an OR

]

我曾尝试过 JavaScript IndexOf 方法,但它让我得到一个 OR'ed 结果,而不是 AND

提前致谢

4

4 回答 4

5

您可以使用以下.filter()方法

var mainArray = [ /* your array here */ ],
    check = ["15", "21"],
    result;

result = mainArray.filter(function(val) {
    for (var i = 0; i < check.length; i++)
        if (val.indexOf(check[i]) === -1)
            return false;    
    return true;
});

console.log(result);

演示:http: //jsfiddle.net/nnnnnn/Dq6YR/

请注意,.filter()IE 直到版本 9 才支持它,但您可以修复.

于 2012-08-09T11:10:55.503 回答
4

使用.filterand .every,您可以过滤每个参数在该行中显而易见的行:

var filter = function(args) {
  return arr.filter(function(row) {
    return args.every(function(arg) {
      return ~row.indexOf(String(arg));  // [15] should search for ["15"]
    });
  });
};

.every在这里有效地进行AND操作;因为OR你可以.some改用。这些数组函数在较新的浏览器上可用。

于 2012-08-09T11:11:24.597 回答
2

还有一个不使用filter()or的解决方案every()

// function

function AndArray(start, check) {

    this.stripArray = function(element, array) {
        var _array = [];
        for(var i = 0; i < array.length; i++)
            for(var j = 0; j < array[i].length; j++)
                if(element == array[i][j]) _array.push(array[i]);
        return _array;
        }

    for(var k = 0; k < start.length; k++)
        if(start.length > 0) start = this.stripArray(check[k], start);

    return start;

    }

// use

var check = [15, 21];

var start= [[ 15, 6 , 8], [3, 21, 56], [15, 3, 21]];

console.log(AndArray(start, check));    
于 2012-08-09T11:10:25.183 回答
0

这应该这样做

var checkURL = function (url) {
  var final = false;
  if (url.indexOf('jpg') > -1) {
    final = true
  }

  if (url.indexOf('jpeg') > -1) {
    final = true
  }

  if (url.indexOf('gif') > -1) {
    final = true
  }

  if (url.indexOf('png') > -1) {
    final = true
  }

  return final
}

于 2018-06-16T00:59:09.607 回答