Search code examples
javascriptarraysfor-loopnested-for-loop

Compare two arrays of objects using nested for loop


I have two arrays of objects that I'm going to compare. If the values in all properties are the same then I want to remove the property in arr1. Below is the arrays with objects. They have the same values but just in a different order. The problem is when I console.log arr1 I always have { foo: '', bar: '594' } left in the array.

const arr1 = [
  { foo: '061', bar: '591' },
  { foo: '061', bar: '592' },
  { foo: '070', bar: '593' },
  { foo: '', bar: '594' }
]

const arr2 = [
  { foo: '061', bar: '591' },
  { foo: '061', bar: '592' },
  { foo: '', bar: '594' },
  { foo: '070', bar: '593' }
]

Below is my nested for loop

for (let i = 0; i < arr1.length; i++) {
      for (let j = 0; j < arr2.length; j++) {
        if (arr1[i].foo === arr2[j].foo
          && arr1[i].bar === arr2[j].bar) {
          arr1.splice(i, 1)
        }
      }
    }

Solution

  • The reason is because whenever you perform a splice function, the array size has been modified, thus the arr1.length will change in each of the iteration of i. In order to solve this, you can consider modifying the i value directly in your loop to restart the comparison.

    const arr1 = [
      { foo: '061', bar: '591' },
      { foo: '061', bar: '592' },
      { foo: '070', bar: '593' },
      { foo: '', bar: '594' }
    ];
    
    const arr2 = [
      { foo: '061', bar: '591' },
      { foo: '061', bar: '592' },
      { foo: '', bar: '594' },
      { foo: '070', bar: '593' }
    ];
    
    for (let i = 0; i < arr1.length; i++) {
      for (let j = 0; j < arr2.length; j++) {
        if (arr1[i].foo === arr2[j].foo && arr1[i].bar === arr2[j].bar) {
          arr1.splice(i, 1);
          // Restart the current i in next iteration
          i--;
          break;
        }
      }
    }
    
    console.log(arr1);