所以,标题大部分都是这样说的,我举一个例子:
var foo = ['one', 'two', 'three'];
var bar = [
{
integer: 1,
string: 'one'
},
{
integer: 3,
string: 'three'
}
];
现在,我想知道如何针对数组foo
中所有对象的每个string
属性获取bar
中每个元素的正匹配列表
答案 0 :(得分:4)
首先,在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
元素匹配的元素。
这是一个实例:
答案 1 :(得分:0)
循环遍历其中一个数组,检查每个项目与另一个项目:
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()
的旧浏览器,或者您可以使用a shim。
答案 2 :(得分:0)
此:
// 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
注意:使用节点以交互方式运行
答案 3 :(得分:0)
这两项工作。取决于您希望如何使用您可以修改的数据。
WAY ONE
//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]);
}
}
}