I have two result sets like this:
const resultSet1 =
[
{
"id": "1",
"version": "3",
"website": "https://xx/version/3",
"name": Ana,
"lastName": Ana,
},
{
"id": "2",
"version": "3",
"website": "https://xx/version/3",
"name": Ana,
"lastName": Ana,
}
]
const resultSet2 =
[
{
"id": "1",
"version": "2",
"birthday": "24.08.1984",
"place": "Europe",
},
{
"id": "2",
"version": "2",
"birthday": "24.08.1984",
"place": "Europe",
},
{
"id": "1",
"version": "1",
"birthday": "24.08.1984",
"place": "Europe",
},
{
"id": "2",
"version": "3",
"birthday": "24.08.1984",
"place": "Europe",
}
]
I want to compare these two result sets, based on id & version. In my const comparisonSet, I want to have elements from the first result set, whose both id & version are not present in the second result set.
const comparisonSet =
[
{
"id": "1",
"version": "3",
"website": "https://xx/version/3",
"name": Ana,
"lastName": Ana,
}
]
How can I achieve this in Javascript?
Any help would be appreciated. Thank you in advance!
Advertisement
Answer
You can use filter to get the desired result.
Overall complexity – O(n * 2)
resultSet1.filter(({ id, version }) =>!resultSet2.find((o) => o.id === id && o.version === version));
const resultSet1 = [{
id: "1",
version: "3",
website: "https://xx/version/3",
name: "Ana",
lastName: "Ana",
},
{
id: "2",
version: "3",
website: "https://xx/version/3",
name: "Ana",
lastName: "Ana",
},
];
const resultSet2 = [{
id: "1",
version: "2",
birthday: "24.08.1984",
place: "Europe",
},
{
id: "2",
version: "2",
birthday: "24.08.1984",
place: "Europe",
},
{
id: "1",
version: "1",
birthday: "24.08.1984",
place: "Europe",
},
{
id: "2",
version: "3",
birthday: "24.08.1984",
place: "Europe",
},
];
const result = resultSet1.filter(
({
id,
version
}) =>
!resultSet2.find((o) => o.id === id && o.version === version)
);
console.log(result);Though it is not so optimized, so you can also create a dictionary and loop up result in O(1) –
Overall complexity O(n)
const dict = resultSet2.reduce((acc, curr) => {
const { id, version } = curr;
acc[`${id}|${version}`] = curr;
return acc;
}, {});
const result = resultSet1.filter(({ id, version }) => !dict[`${id}|${version}`]);
const resultSet1 = [
{
id: "1",
version: "3",
website: "https://xx/version/3",
name: "Ana",
lastName: "Ana",
},
{
id: "2",
version: "3",
website: "https://xx/version/3",
name: "Ana",
lastName: "Ana",
},
];
const resultSet2 = [
{
id: "1",
version: "2",
birthday: "24.08.1984",
place: "Europe",
},
{
id: "2",
version: "2",
birthday: "24.08.1984",
place: "Europe",
},
{
id: "1",
version: "1",
birthday: "24.08.1984",
place: "Europe",
},
{
id: "2",
version: "3",
birthday: "24.08.1984",
place: "Europe",
},
];
const dict = resultSet2.reduce((acc, curr) => {
const { id, version } = curr;
acc[`${id}|${version}`] = curr;
return acc;
}, {});
const result = resultSet1.filter(({ id, version }) => !dict[`${id}|${version}`]);
console.log(result);