簡體   English   中英

多個值的Javascript索引

[英]Javascript index of for multiple values

我有像這樣的多維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.例如,如果檢查數組是[15]那么多維數組就是

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

]

2.例如,如果檢查數組是[15,21]那么多維數組就是

[
    ["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方法BUt它給我一個OR結果而不是AND

提前致謝

您可以使用.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/

請注意,在版本9之前,IE不支持.filter() ,但您可以解決此問題

使用.filter.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代替。 這些數組函數可在較新的瀏覽器上使用。

還有一個不使用filter()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));    

這應該做到這一點

 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 } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM