将数组的字符串元素与另一个数组的对象元素属性进行比较

Compare string elements of an array to object elements property of another array

本文关键字:元素 数组 比较 属性 字符串 另一个 对象      更新时间:2023-09-26

所以,标题说明了大部分内容,我将举一个例子:

var foo = ['one', 'two', 'three'];
var bar = [
        {   
            integer: 1,
            string: 'one'
        },
        {   
            integer: 3,
            string: 'three'
        }       
    ];

现在,我想知道如何获得foo中每个元素与数组bar中所有对象的string属性的正匹配列表。

首先,在foo中创建一组所有元素以避免平方复杂性:

var fooSet = {};    
for(var i = 0; i < foo.length; i++) {
    var e = foo[i];
    fooSet[e] = true;
}

然后,通过bar并收集匹配项:

var matches = [];
for(var i = 0; i < bar.length; i++) {
    var e = bar[i];
    if(fooSet[e.string]) {
           matches.push(e);
    }
}

之后,matches数组将包含来自bar的与foo的元素匹配的元素。

下面是一个活生生的例子:

  • http://jsfiddle.net/mfAc4/

循环通过其中一个数组,将每个项目与另一个进行检查:

var matches = [],
    i, j;
for (i=0; i < bar.length; i++)
    if (-1 != (j = foo.indexOf(bar[i].string)))
       matches.push(foo[j]);
// matches is ['one', 'three']

显然,如果您希望matches包含bar而不是foo中的项,只需将.push()语句更改为matches.push(bar[i]);即可。

当然,以上假设您不关心支持不在数组上执行.indexOf()的旧浏览器,或者您可以使用填充程序。

这两个工作。取决于您希望如何使用可以修改的数据。

http://jsfiddle.net/KxgQW/5/

单向

//wasn't sure which one you want to utilize so I'm doing both
//storing the index of foo to refer to the array
var wayOneArrayFOO= Array();
//storing the index of bar to refer to the array
var wayOneArrayBAR= Array();
var fooLength = foo.length;
var barLength = bar.length;

/*THE MAGIC*/                
//loop through foo
for(i=0;i<fooLength;i++){
    //while your looping through foo loop through bar        
    for(j=0;j<barLength;j++){
        if(foo[i]==bar[j].string){
            wayOneArrayFOO.push(i);
            wayOneArrayBAR.push(j);    
        }
    }
}

双向

//storing the value of foo
var wayTwoArrayFOO= Array();
//storing the value of bar
var wayTwoArrayBAR= Array();            

/*THE MAGIC*/      
//loop through foo
for(i=0;i<fooLength;i++){
    //while your looping through foo loop through bar        
    for(j=0;j<barLength;j++){
        if(foo[i]==bar[j].string){
            wayTwoArrayFOO.push(foo[i]);
            wayTwoArrayBAR.push(bar[j]);    
        }
    }
}

这:

// foo & bar defined here
// put all the keys from the foo array to match on in a dictionary (object)
var matchSet = {};
for (var item in foo)
{
    var val = foo[item];
    matchSet[val] = 1;
}
// loop through the items in the bar array and see if the string prop is in the matchSet
// if so, add it to the matches array
var matches = [];
for (var i=0; i < bar.length; i++)
{
    var item = bar[i];
    if (matchSet.hasOwnProperty(item['string']))
    {
        matches.push(item['string']);
    }
}
// output the matches (using node to output to console)
for (var i in matches)
{
    console.log(matches[i]);
}

输出:

match: one
match: three

注意:使用节点以交互方式运行