问题
给定以下两个数组:
const myArr1 = [
{ locationPath: 'R0', locationOnGrid: { x: '0', y: '0' } }, // same as second in myArr2
{ locationPath: 'U5', locationOnGrid: { x: '1', y: '0' } },
{ locationPath: 'L3', locationOnGrid: { x: '3', y: '7' } } // same as second in myArr2
]
const myArr2 = [
{ locationPath: 'D0', locationOnGrid: { x: '0', y: '0' } }, // same as second in myArr1
{ locationPath: 'L5', locationOnGrid: { x: '3', y: '7' } }, // same as third in myArr1
{ locationPath: 'L7', locationOnGrid: { x: '0', y: '1' } },
{ locationPath: 'R2', locationOnGrid: { x: '2', y: '2' } }
]
// Do something to 'filter' out the objects that are similar.
结果
然后我希望在比较之后也能做的是过滤掉某个结果:
// Result of the 'filter' function
const found = [
{ locationPath: 'R0', locationOnGrid: { x: '0', y: '0' } },
{ locationPath: 'L5', locationOnGrid: { x: '3', y: '7' } }
];
// and want to do something like the following on the found array:
const startingPoint = ({locationOnGrid}) => {
return JSON.stringify(locationOnGrid) !== JSON.stringify({ x: '0', y: '0' });
};
const filteredFound = found.filter(startingPoint);
console.log(filteredFound);
// output:
// Array(1)
// 0: {locationPath: "L5", locationOnGrid: {…}}
到目前为止我尝试了什么:
有一些 Stackoverflow 问题与两个数组之间的比较有关。例如问题 Simplest code for array intersection和 How to filter array by comparing two elements非常接近。
// does not work
const found = myArr2.filter((item, index) => {
return
(
item.locationOnGrid.x === myArr1[index].locationOnGrid.x &&
item.locationOnGrid.y === myArr1[index].locationOnGrid.y
);
});
console.log(found);
另外,两个数组不一定总是具有相同数量的对象。在示例中,myArr2 还有 1 个对象。所以这有效。但对于另一种情况,很可能是 myArr1 比 myArr2 拥有更多的对象。
最佳答案
你可以得到一个 Set
使用规范化的键/值对,按键排序并创建一个 JSON .
然后过滤第一个数组,得到普通的locationOnGrid
对象。
const
stringified = o => JSON.stringify(Object.entries(o).sort((a, b) => a[0].localeCompare(b[0]))),
array1 = [{ locationPath: 'R0', locationOnGrid: { x: '0', y: '0' } }, { locationPath: 'U5', locationOnGrid: { x: '1', y: '0' } }, { locationPath: 'L3', locationOnGrid: { x: '3', y: '7' } }],
array2 = [{ locationPath: 'D0', locationOnGrid: { x: '0', y: '0' } }, { locationPath: 'L5', locationOnGrid: { x: '3', y: '7' } }, { locationPath: 'L7', locationOnGrid: { x: '0', y: '1' } }, { locationPath: 'R2', locationOnGrid: { x: '2', y: '2' } }],
set2 = new Set(array2.map(({ locationOnGrid }) => stringified(locationOnGrid))),
common = array1.filter(({ locationOnGrid }) => set2.has(stringified(locationOnGrid)));
console.log(common);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何将两个数组与对象进行比较以过滤相似的对象(vanilla JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59191159/