我有3个数据源,我正在将数据提取到这些数据源中,只是想拥有具有匹配对象(坐标)的项的新集合。我尝试了几种方法,包括链接下划线方法,但似乎无法以可靠的方式提取多于2种方法。如果我使用嵌套循环,如果父循环没有匹配项,而子循环却有匹配项,那么它会很快变得混乱,如果错过了(如果有道理)。
我还尝试将它们组合成一个大数组,如果这是最简单的方法,那会很好,但无法弄清楚如何找到coord对象的匹配项。
每个数组的结果应该不超过20个,因此性能对我来说并不是真正的问题。非常感谢您的帮助。我已经花了很多时间在不同的解决方案上,并且正要扔掉我的笔记本电脑。
var arrays = [
[{
id: "NMm421ue-NSXOu7Af2CNmg",
name: "name1",
source: 'mapQuest',
coords: {
lat: 35.878,
lng: -78.85
}
}, {
id: "3233e-NSXOu7A3436gdfg",
name: "another name",
source: 'mapQuest',
coords: {
lat: 40.558,
lng: -84.78
}
}],
[{
id: "1234567768",
name: 'googleName',
source: 'google',
coords: {
lat: 35.878,
lng: -78.85
}
}, {
id: "555446888",
name: 'Another Google',
source: 'google',
coords: {
lat: 44.866,
lng: -65.84
}
}],
[{
id: "54sfs2198",
name: 'Personal 1',
source: 'personal',
coords: {
lat: 44.866,
lng: -65.84
}
}, {
id: "98456245f",
name: '2nd personal',
source: 'personal',
coords: {
lat: 35.878,
lng: -78.85
}
}]
];
var result = arrays.shift().filter(function(v) {
console.log('v:', v);
return arrays.every(function(a) {
return a.indexOf(v) !== -1;
});
});
预期结果将是
[
{id:"98456245f", name:'2nd personal', source: 'personal', coords: { lat: 35.878, lng: -78.85 } },
{id:"1234567768", name:'googleName', source: 'google', coords: { lat: 35.878, lng: -78.85 },
{id: "NMm421ue-NSXOu7Af2CNmg", name: "name1", source:'mapQuest', coords: {lat: 35.878, lng: -78.85} }
]
如果您不在乎所有阵列中的重复项来自何处,则可以展平lat
/ lng
对上的集合和组。然后,筛选出任何大小不足以传递大小截止参数threshold
的分组。
请注意,结果以数组数组形式返回,这对我来说最有意义,因为可能会有多个分组。如有必要,呼叫者可以将其展平。
const findCoordDupes = (coords, threshold=2) => {
return Object.values(coords.flat().reduce((a, e) => {
const key = `${e.coords.lat} ${e.coords.lng}`;
if (!a[key]) a[key] = [];
a[key].push(e);
return a;
}, {})).filter(e => e.length > threshold);
};
const coords = [
[{
id: "NMm421ue-NSXOu7Af2CNmg",
name: "name1",
source: 'mapQuest',
coords: {
lat: 35.878,
lng: -78.85
}
}, {
id: "3233e-NSXOu7A3436gdfg",
name: "another name",
source: 'mapQuest',
coords: {
lat: 40.558,
lng: -84.78
}
}],
[{
id: "1234567768",
name: 'googleName',
source: 'google',
coords: {
lat: 35.878,
lng: -78.85
}
}, {
id: "555446888",
name: 'Another Google',
source: 'google',
coords: {
lat: 44.866,
lng: -65.84
}
}],
[{
id: "54sfs2198",
name: 'Personal 1',
source: 'personal',
coords: {
lat: 44.866,
lng: -65.84
}
}, {
id: "98456245f",
name: '2nd personal',
source: 'personal',
coords: {
lat: 35.878,
lng: -78.85
}
}]
];
console.log(findCoordDupes(coords));