Array.prototype.difference

JavaScript's built-in Array object does not have a difference method by default to compare 2 arrays. However, it looks very useful to have it as a bulit-in method:

const a1 = [1, 2, 3]
const a2 = [1, 3]
a1.difference(a2);
// result: [2]

It can accept a custom comparator function. This will give us more flexibility in comparing elements. Here's an example:

const a1 = [1.2, 2.3, 3.9]
const a2 = [1.4, 3.8]
a1.difference(a2, (a, b) => Math.round(a) === Math.round(b));
// result: [2.3]

If we don't provide a comparator function, a default one is assumed to work like this:

(a, b) => a === b

Related: this is being added to Sets:

const s1 = new Set([1, 2 ,3]);
const s2 = new Set([1, 3]);
s1.difference(s2);
// result: new Set([2])

Please do not recommend that people modify objects they don't own; it's not a polyfill until it's in a spec.

I think the main issue here is that your suggestion uses .includes which uses SameValue - it makes a lot more sense to me to take a comparator function that decides whether two things are the same or different.

1 Like

@ljharb Thank you for your input. I've removed the polyfill and incorporated your suggestion to use a comparator function. I appreciate the idea.

This can also be extended to Array.intersection, which is basically the same idea but opposite

1 Like

I like your idea