简体   繁体   中英

javascript return new array of unique elements with .filter()

I have written code to return a new array containing only the unique elements of two seperate arrays. example: [1,2,3] and [1,2] will return 3. I have working code, however I would just like an explanation of why this works when using '!' before my return statement:

function diffArray(arr1, arr2) {
  return arr1.concat(arr2).filter(function(val){
    return !(arr1.indexOf(val) >= 0 && arr2.indexOf(val) >= 0)
  });
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

but this does not:

function diffArray(arr1, arr2) {
  return arr1.concat(arr2).filter(function(val){
    return arr1.indexOf(val) < 0 && arr2.indexOf(val) < 0
  });
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

I was under the impression that '!' would just invert the expression, so excluding it and using a '<' rather than '>=' should return the same value.

According to De Morgan's laws , the equivalent to the expression

!(arr1.indexOf(val) >= 0 && arr2.indexOf(val) >= 0)

is

(arr1.indexOf(val) < 0 || arr2.indexOf(val) < 0)
//                     ^^

The opposite of

a AND b are greater than 0

is not

a AND b are inferior to 0

but

a OR b are inferior to 0

I believe this would work :

function diffArray(arr1, arr2) {
    return arr1.concat(arr2).filter(function(val){
        return arr1.indexOf(val) < 0 || arr2.indexOf(val) < 0
    });                            /*^^*/
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM