Problem
Given the following two arrays:
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
Then what I would like to also be able to do after the comparison has been made, is to filter out a certain result:
// 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: {…}}
What I've tried so far:
There are some Stackoverflow questions that relate to the comparison between two Arrays. For example the question Simplest code for array intersection and How to filter array by comparing two elements comes really close.
// 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);
Also two arrays don't always necessarily have the same amount of objects. In the example myArr2 has 1 more object. So this works. But for another scenario it could very well be that myArr1 has more objects than myArr2.