查找数组中是否包含两个或更多键

时间:2015-11-25 07:11:09

标签: javascript arrays

是否有函数可以查找数组中是否包含两个或更多个键? 如果目标数组包含结果数组中的所有键,我希望函数返回True / False。

//Both must be in the array, not in that order tho.
var target = ['love', 'sweden'];

//Object that i want to search.
var result = [{
    title: "Love in Norway!",
    tags: ['love', 'norway', 'birds', 'summer']
}, {
    title: "Love in Sweden!",
    tags: ['love', 'sweden', 'car', 'blue']
}, {
    title: "I am in Norway!",
    tags: ['mytag', 'sweden', 'summer', 'love']
}, {
    title: "Love in randowm!",
    tags: ['love', 'norway', 'birds', 'summer']
}, ];

myfunction(result[x], target, function (isThere) {
    // isThere of [x] = false;
    // isThere of [x] = true;
    // isThere of [x] = true;
    // isThere of [x] = false;
});

3 个答案:

答案 0 :(得分:1)

有很多方法可以实现它。我已使用reduce实现。

function myFunction(obj, arr) {
   return arr.reduce(function (acc, elem) {
      return acc && obj.tags.indexOf(elem) > -1;
   }, true);
}

console.log(myFunction(result[1], target));

result: true

答案 1 :(得分:1)

正如Isa Bek所说,有很多方法:

function isThere(resultSet,target)
{
    for(var i=0;i<target.length;i++)
    {
        if(resultSet.tags.indexOf(target[i])=== -1)
           {
               return false;
           }
    }
       return true;
};


console.log(isThere(result[0],target)); //false
console.log(isThere(result[1],target)); //true
console.log(isThere(result[2],target)); //true
console.log(isThere(result[3],target)); //false

他们中的大多数人都会使用indexOf来检查if a value is in an array

答案 2 :(得分:1)

不区分大小写的解决方案:

var searchWords = ['love', 'sweden'],
    searchArray = [
            {
              title: "Love in Norway!",
              tags: ['love', 'norway', 'birds', 'summer']
            },
            {
              title: "Love in Sweden!",
              tags: ['love', 'sweden', 'car', 'blue']
            },
            {
              title: "I am in Norway!",
              tags: ['mytag', 'SWEDEN', 'summer', 'love']
            },
            {
                title: "Love in randowm!",
                tags: ['love', 'norway', 'birds', 'summer']
            }
    ];

function parser( needle, target ) {
    // Recurring search of needle e.g. first value will be "love"
    needle.forEach( function( searchTag ) {
        // Recurring search of target e.g. first value will be { title: "Love in Norway!", tags: ['love', 'norway', 'birds', 'summer'] }    
        target.forEach( function ( obj ) {
            // See if searchTag exists in tags. If jQuery is on the table then $.inArray() is far more powerfull
            if ( obj.tags.indexOf(searchTag) > -1 ){
                // Your awesome code
                alert ('found "' + searchTag + '" in ' + obj.title );
            }
        } );
    } );
}
parser( searchWords, searchArray );