I have an array of objects:
const array = [{
"colour": "red",
"job": "student",
"title": "Mr",
},
{
"colour": "green",
"job": "student",
"title": "",
},
{
"colour": "",
"job": "teacher",
"title": "Mr",
},
{
"colour": "red",
"job": "student",
"title": "Mr",
}}]
I would like to compare the objects inside the array with each other.
What I have so far does not seem efficient as I would be comparing index i=1 and j=2 and i=2 and j=1 which is comparing exactly the same object. I am using Lodash _.isEqual() to compare the objects.
const handleArrayItems = () => {
for (let i = 0; i <= array.length; i++) {
for (let j = 1; j < array.length; j++) {
if (j === i) {
continue; //to avoid comparing same object
}
if (_.isEqual(array[j],array[i])) {
return true;
}
}
}
};
Based on what is returned from above, it is passed into an if/else statement.
if (handleArrayItems()) {
console.log("found a duplicate item in array")
}
handleArrayItems()will return true if there is a match and false is no object items are the same