Comparing objects in JavaScript and return array of common keys having common values

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two objects. The function should return an array of all those common keys that have common values across both objects.


The code for this will be −

const obj1 = { a: true, b: false, c: "foo" };
const obj2 = { a: false, b: false, c: "foo" };
const compareObjects = (obj1 = {}, obj2 = {}) => {
   const common = Object.keys(obj1).filter(key => {
      if(obj1[key] === obj2[key] && obj2.hasOwnProperty(key)){
         return true;
      return false;
   return common;
console.log(compareObjects(obj1, obj2));


And the output in the console will be −

['b', 'c']
Updated on 20-Nov-2020 09:47:10