这方面有很多帖子,但是我的JS印章还在那里为我的案例找到解决方案。
我有两个数组,一个是Google Lat / Lng变量的硬编码数组(屏幕截图中的Array2),另一个是迭代DOM元素(截图中的Array1)构建的数组。我需要将Array2与DOM中动态创建的Array1进行比较,并创建一个只有Array1中找到的Array2对象的新Array3。这将是我迭代创建地图标记的数组。以下是我的代码示例。
数组1
var gdata = new Array();
$("table tbody tr:gt(0)").each(function (i) {
gdata[i] = new Array();
$(this).children('td').each(function (ii) {
gdata[i][ii] = $(this).text();
});
});
ARRAY2
var markers = [
['a0', 32.840801, -117.244842],
['a10', 32.840801, -117.244842],
['a20', 32.840777, -117.244864],
...
]
答案 0 :(得分:1)
我认为你应该使用类似的东西:
var results = []; // the results array
for (var i = 0; i < markers.length; i++) // iterate for every marker key
{
results = results.concat(gdata.filter(function(item) { return item[8] == markers[i][0]; }));
}
在js中,我们可以使用过滤器方法,以便通过查询语句仅检索给定数组的一部分。在这种情况下,我们使用每个标记键与整个gdata的比较array ..最后 - 我们将每个标记的相关项目与目标结果数组相结合
答案 1 :(得分:1)
由于您的检查似乎只处理HTML表格第一列中的值,因此您无需在gdata
中只读取第一列中的所有值。然后,您可以将文本从第一列转换为文本为键的对象,以便更快地查找:
var gdata = {};
$("table tbody tr:gt(0)>td:first-child").each(function () {
gdata[$(this).text()] = true;
});
var markers = [
['a0', 32.840801, -117.244842],
['a10', 32.840801, -117.244842],
['a20', 32.840777, -117.244864],
['c3', 32.840777, -117.244864],
];
var array3 = markers.filter(function(row) {
return row[0] in gdata;
});
console.log(array3);
td, th { font-size: 9px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing=0 cellpadding=0 border=1>
<tr>
<th>heading</th><th>heading</th><th>heading</th>
</tr>
<tr>
<td>b</td><td>123</td><td>123</td>
</tr>
<tr>
<td>a20</td><td>123</td><td>123</td>
</tr>
<tr>
<td>a0</td><td>123</td><td>123</td>
</tr>
</table>
如果您有ES6支持,则可以改为使用Set
和箭头功能:
var gdata = new Set($("table tbody tr:gt(0)>td:first-child")
.map( (i,td) => $(td).text()).get());
var markers = [
['a0', 32.840801, -117.244842],
['a10', 32.840801, -117.244842],
['a20', 32.840777, -117.244864],
['c3', 32.840777, -117.244864],
];
var array3 = markers.filter( ([id]) => gdata.has(id) );
console.log(array3);
td, th { font-size: 9px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing=0 cellpadding=0 border=1>
<tr>
<th>heading</th><th>heading</th><th>heading</th>
</tr>
<tr>
<td>b</td><td>123</td><td>123</td>
</tr>
<tr>
<td>a20</td><td>123</td><td>123</td>
</tr>
<tr>
<td>a0</td><td>123</td><td>123</td>
</tr>
</table>
答案 2 :(得分:0)
听起来你想要filter()
静态列表,如果它们中的任何一个(some()
)与动态列表匹配:
var markers = [
['a0', 32.840801, -117.244842],
['a10', 32.840801, -117.244842],
['a20', 32.840777, -117.244864]
];
var dynamic = [
['a0', 32.840801, -117.244842],
['a0zz', 32.840801, -117.244842]
];
var found = markers.filter( m => dynamic.some( d => d[0] === m[0]) );
console.log(found)
&#13;