When working with Rest APIs, it is sometimes necessary to compare data returned to the backend with data modified by the user in the frontend.
To solve this issue, you can compare the array of data using filter()
and some()
array methods.
In this approach, we use the filter()
method on the first array and check if each item doesn't have the same value for name and age — checking it with some()
. Then, we do the opposite for the second array. And we return the concatenated array from the result of the comparison.
Reminder
For this comparison, we compare the difference between two objects on their value on name and age properties. If you have more criteria, you should add them in the
For this comparison, we compare the difference between two objects on their value on name and age properties. If you have more criteria, you should add them in the
some()
methods below.Demonstration
const arr1 = [
{id: 1, name: 'Tommy', age: 12},
{id: 2, name: 'Alphonse', age: 21},
{id: 3, name: 'Albert', age: 25},
{id: 4, name: 'Sophia', age: 23},
{id: 5, name: 'Arsene', age: 30},
{id: 6, name: 'Kevin', age: 30},
{id: 7, name: 'Rebecca', age: 31}
];
const arr2 = [
{id: 1, name: 'Tommy', age: 12},
{id: 2, name: 'Sophia', age: 23},
{id: 3, name: 'Albert', age: 25},
{id: 4, name: 'Kevin', age: 27},
{id: 5, name: 'Arsene', age: 30},
{id: 6, name: 'Maxime', age: 17}
];
function getDifference(array1, array2) {
const diffFromA1toA2 = array1.filter(
obj1 => !array2.some(obj2 => obj1.name === obj2.name && obj1.age === obj2.age)
);
const diffFromA2toA1 = array2.filter(
obj2 => !array1.some(obj1 => obj2.name === obj1.name && obj2.age === obj1.age)
);
return [...diffFromA1toA2, ...diffFromA2toA1];
}
console.log(getDifference(arr1, arr2));
// 👇️ See the output below
[
{ id: 2, name: 'Alphonse', age: 21 },
{ id: 6, name: 'Kevin', age: 30 },
{ id: 7, name: 'Rebecca', age: 31 },
{ id: 4, name: 'Kevin', age: 27 },
{ id: 6, name: 'Maxime', age: 17 }
]
🎒More ressources
Learn about the some() method →
Learn about the filter() method →
Author : Kevin Kouomeu
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments. Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments. Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium