Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all objects in an array contains same keys and values?

Tags:

How to check if all objects in an array contains same keys and values

const arrOfObjects = [{a: 1, b: 2}, {a: 1, b: 2}, {a:1, b: 2 }] // true

const arrOfObjects = [{a: 1, b: 2}, {a: 1, b: 2}, {a:2, b: 1 }] //false

const arrOfObjects = [{a: 1, b: 2}, {a: 1, b: 2, c: 3}, {a:2, b: 1 }] //false

This is my trial that looks so ugly and bad and not working, i would be thankful if someone put an efficient code for that problem!

function test(arr){

   const firstItem = arr[0];
   const firstItemKeys = Object.keys(firstItem);

   for(let i = 0; i < firstItemKeys.length; i++) {
      for(let j = 0; j < arr.length; j++) {
         for(let x in arr[j]) {
             if(arr[j][x] !== firstItem[firstItemKeys[i]]) return false
         }
       }
   }

   return true
}
like image 796
Code Eagle Avatar asked Jun 18 '20 23:06

Code Eagle


2 Answers

Here is the code:

const arrOfObjects = [
  { a: 1, b: 2 },
  { a: 1, b: 2 },
  { b: 2, a: 1 },
]
function areEquals(a, b) {
  var keys1 = Object.keys(a)
  var keys2 = Object.keys(b)
  if(keys1.length !== keys2.length) {
    return false ;
  }
  for(key in a) {
    if(a[key] !== b[key])  return false;
  }
  return true ;
}
function checkArray(arr) {
  for (var i = 1; i < arr.length; i++) {
    if (!areEquals(arr[0], arr[i])) return false
  }
  return true
}
console.log(checkArray(arrOfObjects))
like image 59
Ehsan Nazeri Avatar answered Sep 22 '22 11:09

Ehsan Nazeri


If you can use lodash, then there is method _.isEqual

const _ = require('lodash')
const arrOfObjects = [{a: 1, b: 2}, {a: 1, b: 2}, {a:1, b: 2 }]
let isEqual = true
arrOfObjects.forEach(obj => {
  if (!_.isEqual(arrOfObjects[0], obj)) {
    isEqual = false
  } 
})

return isEqual

PS: This could be written in one line with reduce, but it will not be readable for anyone new to programming or javascript.

like image 26
libik Avatar answered Sep 20 '22 11:09

libik