Как сравнить объекты js?

Напишите функцию compare для сравнения двух объектов по ссылке. Если передать функции две ссылки на один и тот же объект, она должна возвращать true, иначе — false.

function compare(firstObj, secondObj) {
    // напишите ваш код здесь
}

const first = {
  property: 'value'
};

const second = {
  property: 'value'
};

const third = second;

compare(first, second); // false
compare(second, third); // true 

Вот мое решение:

function compare(firstObj, secondObj) {
  if ( firstObj === secondObj ) return true;
    

  if ( ! ( firstObj instanceof Object ) || ! ( secondObj instanceof Object ) ) return false;
   

  if ( firstObj.constructor !== secondObj.constructor ) return false;
   

  for ( var p in firstObj ) {
    if ( ! firstObj.hasOwnProperty( p ) ) continue;
     

    if ( ! secondObj.hasOwnProperty( p ) ) return false;
      

    if ( firstObj[ p ] === secondObj[ p ] ) continue;
      

    if ( typeof( firstObj[ p ] ) !== "object" ) return false;
    

    if ( ! object_equals( firstObj[ p ],  secondObj[ p ] ) ) return false;
   
  }

  for ( p in secondObj )
    if ( secondObj.hasOwnProperty( p ) && ! firstObj.hasOwnProperty( p ) )
      return false;
   

  return true;
}


const first = {
  property: 'value'
};

const second = {
  property: 'value'
};

const third = second;

console.log(compare(first, second)); // false
console.log(compare(second, third)); // true

еще решала так

function isEqual(firstObj, secondObj) {
  const a = JSON.stringify(firstObj);
  const b = JSON.stringify(secondObj);
  if(a == b){
    return true
  } else {
    return false
  }
}

const first = {
  property: 'value',
  anotherProperty: 'another value'
};

const second = {
  property: 'value',
  anotherProperty: 'another value'
};

const third = {
  property: 'value',
  anotherProperty: 'one more value'
};

console.log(isEqual(first, second));
console.log(isEqual(second, third))

isEqual(first, second); // true
isEqual(second, third); // false

Все равно выдает ошибкую, в обоих вариантахю помогите, пожалуйста.


Ответы (2 шт):

Автор решения: nazarpunk

const compare = (firstObj, secondObj) => firstObj === secondObj;

const first = {property: 'value'};
const second = {property: 'value'};
const third = second;

console.log(
compare(first, second), // false
compare(second, third) // true 
);

→ Ссылка
Автор решения: anti1hero
function compare(firstObj, secondObj) {
if (firstObj === secondObj){
  return true
}
  else{
      return false

  }
}
→ Ссылка