9

I'm fighting with a custom comparison functions for Lodash's _.isEqualWith. I'd like a function such that this is works:

const comparisonFunc = /* ...TBC... */

// Should be true:
_.isEqualWith({ a: undefined }, { }, comparisonFunc);

// Should still be false, as normal:
_.isEqualWith({ a: undefined }, { a: 123 }, comparisonFunc);

// Should still be false, as normal:
_.isEqualWith([undefined], [ ], comparisonFunc);

I.e. for any object in the comparison (recursively), properties set to undefined should be treated as if they didn't exist.

3
  • Doesn't seem like it's possible. It seems like if the keys of the first two arguments don't match, then the method doesn't do a recursive comparison of all the values. You can either create all matching keys for both objects or write some other function to do the comparison instead.
    – VLAZ
    Commented Sep 10, 2019 at 16:53
  • so is it a flat level data, or the data can go upto any depth. the examples are just flat in data (object or array) but is the question for and depth? Commented Sep 11, 2019 at 11:04
  • @KoushikChatterjee yes, any depth. It work recursively, like isEqualWith does normally.
    – Tim Perry
    Commented Sep 11, 2019 at 13:28

5 Answers 5

5

It's not as simple as I'd like, but I found a solution for this:

const comparisonFunc = (a, b) => {
    if (_.isArray(a) || _.isArray(b)) return;
    if (!_.isObject(a) || !_.isObject(b)) return;

    if (!_.includes(a, undefined) && !_.includes(b, undefined)) return;

    // Call recursively, after filtering all undefined properties
    return _.isEqualWith(
        _.omitBy(a, (value) => value === undefined),
        _.omitBy(b, (value) => value === undefined),
        comparisonFunc
    );
}


// Should be true:
_.isEqualWith({ a: undefined }, { }, comparisonFunc); // = true

// Should still be false, as normal:
_.isEqualWith({ a: undefined }, { a: 123 }, comparisonFunc); // = false

// Should still be false, as normal:
_.isEqualWith([undefined], [ ], comparisonFunc); // = false

Happy to accept other answers if anybody has something simpler or better though :-)

5
  • Try avoiding omitBy instead use pickBy, the way you are doing it is right but too much of code and and not a simple one to read.. Commented Sep 16, 2019 at 16:27
  • Unfortunately lodash isEqualWith is not capable to solve such question - it is not possible to handle inherited objects with undefined properties. If you are going to return undefined than you are loosing control of any child comparison.
    – puchu
    Commented Jul 7, 2021 at 13:30
  • 1
    @puchu isEqualWith always applies recursively, so you don't lose control of child comparison by returning undefined. With the above for example, _.isEqualWith([{ a: undefined }], [{ }], comparisonFunc) returns true, even though undefined is returned when the top-level array is encountered. This seems to work for me, do you have an example where it fails?
    – Tim Perry
    Commented Jul 7, 2021 at 13:59
  • Sorry, I had wrong understanding of isEqualWith: it passes next object and array comparison to customizer once again.
    – puchu
    Commented Jul 7, 2021 at 14:15
  • 1
    For future visitors, here is a link to the relevant docs. The first three cases in comparisonFunc work because when the comparison function returns undefined, the default is used (recursively). Commented Dec 30, 2022 at 19:53
0

You can just check wheather is is an array or object and filter undefined members accordingly, and call recursively thats it.

const comp = (a, b) => {
  var A, B,
      fn = v => !_.isUndefined(v),
      filter = _.isArray(a)  ? _.filter : _.pickBy;
	if (_.isObject(a)) {
		A = filter(a, fn)
		B = filter(b, fn)
	} else { return _.isEqual(a, b); } 

	if (_.keys(a).length === _.keys(A).length && _.keys(b).length === _.keys(B).length) {return}
	return _.isEqualWith(A, B, comp);
};

var a1 = [10, 10, undefined, undefined, 10],
    a2 = [undefined, undefined, 10, undefined, 10, undefined, 10],
    o1 = {x: 10, y:undefined, z: 20, v: a1}
    o2 = {x: 10, z: 20, v: a2};

console.log('a1 with a2: ', _.isEqualWith(a1, a2, comp));
console.log('o1 with o2: ', _.isEqualWith(o1, o2, comp));
console.log('a1 with o2: ', _.isEqualWith(a1, o2, comp));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Checking the key length and the return statement is there to identify wherher we have to travarse inside (we have removed undefined in last iteration) or we need to travarse it again (as we removed the undefined values in this iteration)

0

The same as Tim Perry's answer, only with TypeScript and lodash/fp


function matchMissingWithUndefined(a: {}, b: {}) {
  const hasUndefined = _.includes(undefined);
  if (_.isPlainObject(a) && _.isPlainObject(b) && (hasUndefined(a) || hasUndefined(b))) {
    const onlyDefined = _.omitBy((value) => value === undefined);
    return _.isEqualWith(matchMissingWithUndefined, onlyDefined(a), onlyDefined(b));
  }
}

_.isEqualWith(matchMissingWithUndefined, { a: undefined }, { }); // true

0

After omitting null values we should somehow bypass initial call to customizer without checking that object does not includes null values once again.

I've invented some sort of nice bike for such purpose:

const compareWithoutNullProperties = (a: any, b: any) =>
  isPlainObject(a) && isPlainObject(b)
    ? isEqualWith(
      omitBy(a, (value) => value == null),
      omitBy(b, (value) => value == null),
      (a: any, b: any, key?: number | string | symbol): boolean | undefined =>
        // Next initial call should be ignored.
        key != null ? compareWithoutNullProperties(a, b) : undefined,
    )
    : undefined;

const isEqualWithoutNullProperties = (a: any, b: any) =>
  isEqualWith(a, b, compareWithoutNullProperties);

Tests returning true:

isEqualWithoutNullProperties({ a: undefined }, {});
isEqualWithoutNullProperties({ a: null }, {});
isEqualWithoutNullProperties([{ a: undefined }], [{}]);
isEqualWithoutNullProperties([{ a: null }], [{}]);
isEqualWithoutNullProperties({ a: { a: undefined } }, { a: {} });
isEqualWithoutNullProperties({ a: { a: null } }, { a: {} });
isEqualWithoutNullProperties({ a: [{ a: undefined }] }, { a: [{}] });
isEqualWithoutNullProperties({ a: [{ a: null }] }, { a: [{}] });

Tests returning false:

isEqualWithoutNullProperties([undefined], []);
isEqualWithoutNullProperties([null], []);
isEqualWithoutNullProperties([undefined], [1]);
isEqualWithoutNullProperties([null], [1]);
isEqualWithoutNullProperties({ a: undefined }, { a: 1 });
isEqualWithoutNullProperties({ a: null }, { a: 1 });
isEqualWithoutNullProperties([{ a: undefined }], [{ a: 1 }]);
isEqualWithoutNullProperties([{ a: null }], [{ a: 1 }]);
isEqualWithoutNullProperties({ a: { a: undefined } }, { a: { a: 1 } });
isEqualWithoutNullProperties({ a: { a: null } }, { a: { a: 1 } });
isEqualWithoutNullProperties({ a: [{ a: undefined }] }, { a: [{ a: 1 }] });
isEqualWithoutNullProperties({ a: [{ a: null }] }, { a: [{ a: 1 }] });
0

We can simply preprocess objects before compare

_.isEqual(_.omitBy({ a: undefined }, _.isNil), _.omitBy({}, _.isNil)); // true
_.isEqual(_.omitBy({ a: undefined }, _.isNil), _.omitBy({ a: 123 }, _.isNil)); // false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.