Why the underscore difference only works in one direction

If I said: "What is the difference between these arrays? ['A'] and ['a', 'b']? Would you say" b "correctly?

I was wondering what is the reason why underlining does not have bidirectional differentiation by default? And how would you combine 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']no matter what order is passed to the arrays.

+4
source share
3 answers

.

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");

, _, , _.mixin

_.mixin({
    absDifference: function(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");
+5

.difference, PHP array_diff, , , , .

, " a, b", " b, " "- .

, , , .

+2

_.difference takes a variable number of arrays as an argument:

Similarly, but returns values ​​from an array not found in other arrays

Thus, it allows only unidirectional design work.

0
source

Source: https://habr.com/ru/post/1534256/


All Articles