Home > OS >  Compare each item in an array of objects
Compare each item in an array of objects

Time:10-26

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")
}

CodePudding user response:

Separate objects are not equal to each other.

if (_.isEqual(array[j] === array[i])) {

will evaluate the argument first:

array[j] === array[i]

which is false, resulting in:

if (_.isEqual(false)) {

which doesn't work.

You need to pass both values to isEqual for comparison

if (_.isEqual(array[j], array[i])) {

so that Lodash can compare the values itself.

CodePudding user response:

Make j goes from i 1 to array.length to doing comparison twice.

And i can go to length-1 only, since j will go to the end.

for (let i = 0; i <= array.length-1; i  ) {
    for (let j = i 1; j < array.length; j  ) {
  • Related