将数组的字符串元素与另一个数组的对象元素属性进行比较
Compare string elements of an array to object elements property of another array
所以,标题说明了大部分内容,我将举一个例子:
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
注意:使用节点以交互方式运行
相关文章:
- 在函数中添加数组元素的数值
- 访问JSON对象内部的数组元素
- 用于检查数组中是否存在元素的javascript自定义方法
- 在数组中的一个元素上设置多个值
- 从组件状态的数组中删除元素
- Mongoose-在更新中删除数组元素
- 从数组中删除元素的最佳方法是:javascript/jquery
- 数组中元素(字符串)的总和
- javascript数组元素是否知道其封闭数组
- 查找数组javascript中包含的元素类型
- 如何在javascript上向数组的对象添加新元素
- 如果数组仍在执行,async.forEach()将运行我添加到数组中的新元素
- 使用filter和map方法将数组中某些元素的第一个字母大写-JavaScript
- 一些元素没有从数组中删除
- JS.循环遍历多维数组,以计数元素在每列中的出现次数
- 将数组元素附加到FormData dos'不适用于Firefox 15
- 元素不会添加到Javascript数组中
- 如何从另一个带下划线的数组中筛选带元素的数组
- 如何将函数应用于两个数组的第 n 个元素(数组的数组)
- Js接受两个值之间的元素(数组)