skip to Main Content

I have two array of objects with different key/value pair. I want to match these if it doesnt match then console log the unmatched object.

array1=[
{'mobile': '24pp'},
{'android': '30pp'},
{ 'ios': '23pp'}
]

array2=[
{'ios': '23pp'},
{'android': '30pp'},
{'mobile': '24pp'}
]

If we try to compare array1 and array2, it should return true

array3=[
{'ios': '23pp'},
{'android': '30pp'},
{'mobile': '30pp'}
]

If we try to compare array1 and array3, it should return false and return {mobile: '24pp'}

Here is my code example but it compares objects one to one but in my case it can be in any order.

const array1 = [{
    'mobile': '24pp'
  },
  {
    'android': '30pp'
  },
  {
    'ios': '23pp'
  }
]

const array2 = [{
    'ios': '23pp'
  },
  {
    'android': '30pp'
  },
  {
    'mobile': '24pp'
  }
]

const array3 = [{
    'ios': '23pp'
  },
  {
    'android': '30pp'
  },
  {
    'mobile': '30pp'
  }
]

function objectsMatch(obj1, obj2) {
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);

  if (keys1.length !== keys2.length) {
    return false;
  }

  // Iterate through the keys and compare their values
  for (const key of keys1) {
    if (obj1[key] !== obj2[key]) {
      return false;
    }
  }

  // If all key-value pairs match, return true
  return true;
}


for (let i = 0; i < 4; i++) {
  console.log('matched ' + objectsMatch(array1[i], array2[i]));

}

3

Answers


  1. Don’t compare the corresponding indexes. For each object in one array, use some() to check if a matching object exists in the other array.

    Use every() to test if all elements in the array have a match in the other array.

    function objectsMatch(obj1, obj2) {
      const keys1 = Object.keys(obj1);
      const keys2 = Object.keys(obj2);
    
      if (keys1.length !== keys2.length) {
        return false;
      }
    
      // Iterate through the keys and compare their values
      for (const key of keys1) {
        if (obj1[key] !== obj2[key]) {
          return false;
        }
      }
    
      // If all key-value pairs match, return true
      return true;
    }
    
    function compareArrays(a1, a2) {
      if (a1.length != a2.length) {
        return false;
      }
      return a1.every(el1 => {
        return a2.some(el2 => objectsMatch(el1, el2));
      });
    }
    
    const array1 = [{
        'mobile': '24pp'
      },
      {
        'android': '30pp'
      },
      {
        'ios': '23pp'
      }
    ]
    
    const array2 = [{
        'ios': '23pp'
      },
      {
        'android': '30pp'
      },
      {
        'mobile': '24pp'
      }
    ]
    
    const array3 = [{
        'ios': '23pp'
      },
      {
        'android': '30pp'
      },
      {
        'mobile': '30pp'
      }
    ]
    
    console.log("Compare array1 and array2");
    console.log(compareArrays(array1, array2));
    console.log("Compare array1 and array3");
    console.log(compareArrays(array1, array3));
    Login or Signup to reply.
  2. You could compare the length of the keys. If they are the same, you should then check every other object. This works for n-number of items.

    Note: After the keys are determined to be the same length, you need to transform the sub-array of objects into one object.

    const data = [
      [{ 'android' : '30pp' }, { 'ios'     : '23pp' }, { 'mobile'  : '24pp' }],
      [{ 'android' : '30pp' }, { 'mobile'  : '24pp' }, { 'ios'     : '23pp' }],
      [{ 'ios'     : '23pp' }, { 'android' : '30pp' }, { 'mobile'  : '24pp' }],
      [{ 'ios'     : '23pp' }, { 'mobile'  : '24pp' }, { 'android' : '30pp' }],
      [{ 'mobile'  : '24pp' }, { 'android' : '30pp' }, { 'ios'     : '23pp' }],
      [{ 'mobile'  : '24pp' }, { 'ios'     : '23pp' }, { 'android' : '30pp' }]
    ];
    
    const areAllEqual = (...items) => {
      if (items.length < 2) return false;
      const [keys, ...otherKeys] = items.map(arr =>
        [...arr.reduce((set, obj) => set.add(...Object.keys(obj)), new Set)]);
      if (otherKeys.some((other) => other.length !== keys.length)) return false;
      const [obj, ...otherObjs] = items.map(arr => Object.assign({}, ...arr));
      return otherObjs.every(otherObj =>
        keys.every(key => otherObj[key] === obj[key]));
    }
    
    console.log('Are all equal?', areAllEqual(...data)); // Verify all permutations
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    Login or Signup to reply.
  3. Given that the arrays have the same keys just make an object from the first array and loop the second and check whether a value with the same key in the object is the same:

    const compare = (arr1, arr2) => {
      const map = {};
      for(let i=0;i<arr1.length;i++){
        for(const k in arr1[i]){
          map[k] = arr1[i][k];
        }
      }
      for(let i=0;i < arr2.length;i++){
        const item = arr2[i];
        for(const k in item){
          if(map[k] !== item[k]){
            return false;
          }
        }
      }
      return true;
    }
    console.log('array1 === array2 : ' , compare(array1, array2));
    console.log('array1 === array3 : ' , compare(array1, array3));
    <script>
    const array1=[
    {'mobile': '24pp'},
    {'android': '30pp'},
    { 'ios': '23pp'}
    ]
    
    const array2=[
    {'ios': '23pp'},
    {'android': '30pp'},
    {'mobile': '24pp'}
    ]
    const array3 = [{
        'ios': '23pp'
      },
      {
        'android': '30pp'
      },
      {
        'mobile': '30pp'
      }
    ]
    </script>

    And a benchmark with 10 items:

    ![enter image description here

    <script benchmark data-count="500000">
    
    const array1=[
    {'mobile': '24pp'},
    {'android': '30pp'},
    { 'ios': '23pp'},
    {'1thing1' : '20pp'},
    {'2thing2' : '20pp'},
    {'3thing3' : '20pp'},
    {'4thing4' : '20pp'},
    {'5thing5' : '20pp'},
    {'6thing6' : '20pp'},
    {'7thing7' : '20pp'},
    
    ]
    
    const array2=[
    {'ios': '23pp'},
    {'android': '30pp'},
    {'mobile': '24pp'},
    {'1thing1' : '20pp'},
    {'2thing2' : '20pp'},
    {'3thing3' : '20pp'},
    {'4thing4' : '20pp'},
    {'5thing5' : '20pp'},
    {'6thing6' : '20pp'},
    {'7thing7' : '20pp'},
    ]
    const array3 = [
    {'1thing1' : '20pp'},
    {'2thing2' : '20pp'},
    {'3thing3' : '20pp'},
    {'4thing4' : '20pp'},
    {'5thing5' : '20pp'},
    {'6thing6' : '20pp'},
    {'7thing7' : '20pp'},
    {
        'ios': '23pp'
      },
      {
        'android': '30pp'
      },
      {
        'mobile': '30pp'
      }
    ]
    
    // @benchmark Polywhirl
    
    const areAllEqual = (...items) => {
      if (items.length < 2) return false;
      const [keys, ...otherKeys] = items.map(arr =>
        [...arr.reduce((set, obj) => set.add(...Object.keys(obj)), new Set)]);
      if (otherKeys.some((other) => other.length !== keys.length)) return false;
      const [obj, ...otherObjs] = items.map(arr => Object.assign({}, ...arr));
      return otherObjs.every(otherObj =>
        keys.every(key => otherObj[key] === obj[key]));
    }
    
    // @run
    
    [areAllEqual(array1, array2) , areAllEqual(array1, array3)]
    
    
    // @benchmark Barmar
    
    function objectsMatch(obj1, obj2) {
      const keys1 = Object.keys(obj1);
      const keys2 = Object.keys(obj2);
    
      if (keys1.length !== keys2.length) {
        return false;
      }
    
      // Iterate through the keys and compare their values
      for (const key of keys1) {
        if (obj1[key] !== obj2[key]) {
          return false;
        }
      }
    
      // If all key-value pairs match, return true
      return true;
    }
    
    function compareArrays(a1, a2) {
      if (a1.length != a2.length) {
        return false;
      }
      return a1.every(el1 => {
        return a2.some(el2 => objectsMatch(el1, el2));
      });
    }
    
    
    // @run
    [compareArrays(array1, array2), compareArrays(array1, array3)];
    
    
    // @benchmark Alexander equal
    const compare = (arr1, arr2) => {
      const map = {};
      for(let i=0;i<arr1.length;i++){
        for(const k in arr1[i]){
          map[k] = arr1[i][k];
        }
      }
      for(let i=0;i < arr2.length;i++){
        const item = arr2[i];
        for(const k in item){
          if(map[k] !== item[k]){
            return false;
          }
        }
      }
      return true;
    }
    // @run
    [compare(array1, array2), compare(array1, array3)];
    
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search