Javascript compare objects having functions using lodash isEqual

As the lodash documentation states:

Functions and DOM nodes are not supported.

https://lodash.com/docs#isEqual


Try isEqualWith instead:

import { isEqualWith, isFunction } from 'lodash-es'

const o1 = { fn() {} }

const o2 = { fn() {} }

const equal = isEqualWith(o1, o2, (v1, v2) =>
  // if `customizer` returns `undefined`, comparisons are handled by the method instead
  isFunction(v1) && isFunction(v2) ? `${v1}` === `${v2}` : undefined,
)

console.log({ equal }) // { equal: true }

This is what I tried:

_.isEqual(o1, o2, function(val1, val2) {
  if(_.isFunction(val1) && _.isFunction(val2)) {
    return val1.toString() === val2.toString();
  }
})

Lodash supports a customizer function which allows you to write your own equality checks. This seems to be a good enough test to see if the functions are character by character the same.


Are you sure you want to compare functions? If you only care about comparing every property that isn't a function, this is easy to do with lodash:

var o1 = { a: 1, b: 2, c: function() { return 1; } },
    o2 = { a: 1, b: 2, c: function() { return 1; } };

_.isEqual(o1, o2)
// → false

_.isEqual(_.omit(o1, _.functions(o1)), _.omit(o2, _.functions(o2)));
// → true

The functions() function returns a list of function properties, and using omit(), you can get rid of them.