0

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")
}
2
  • what is expected output ? Commented Oct 25, 2021 at 4:44
  • handleArrayItems() will return true if there is a match and false is no object items are the same Commented Oct 25, 2021 at 4:49

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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++) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.