Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does underscore's difference only work one way

If I was to say "What is the difference between these arrays? ['a'] and ['a', 'b']?" you would say 'b' right?

I was wondering what the reason is for underscore to not have an bidirectional diff by default? And how would you combine the other methods to achieve this?

var a = ['js-email'],
    b = ['js-email', 'form-group'],
    c = _.difference(a, b), // result: []
    d = _.difference(b, a); // result: ["form-group"]

http://jsfiddle.net/GH59u/1/

To clarify I would like the difference to always equal ['form-group'] regardless of what order the arrays are passed.

like image 579
Dominic Avatar asked Mar 20 '23 01:03

Dominic


1 Answers

You can just combine the differences between the two items in two directions.

function absDifference(first, second) {
    return _.union(_.difference(first, second), _.difference(second, first));
}

console.assert(absDifference(["a", "b"], ["a", "c"]).toString() == "b,c");
var a = ["js-email"], b = ["js-email", "form-group"];
console.assert(absDifference(a, b).toString() == "form-group");

If you want this to be available as part of _ library itself, throughout your project, then you can make use of _.mixin like this

_.mixin({
    absDifference: function(first, second) {
        return _.union(_.difference(first, second), _.difference(second, first));
    }
});

and then

console.assert(_.absDifference(["a", "b"], ["a", "c"]).toString() == "b,c");
var a = ["js-email"],
    b = ["js-email", "form-group"];
console.assert(_.absDifference(a, b).toString() == "form-group");
like image 76
thefourtheye Avatar answered Apr 01 '23 19:04

thefourtheye