-2

Please tell me how to remove all array that duplicates. Example

let arr1=['a', 'b', 'c', 'd']
let arr2=['a', 'e', 'd', 'f', 'p']

I want result like that

let arr3=['b', 'c', 'f', 'p']

please script in javascript or aggregate MongoDB

Yogi
  • 579
  • 1
  • 5
  • 20
srey pick
  • 17
  • 4
  • I assume "e" is meant to be in the result, since that's not duplicated in both arrays? In which case: `arr1.concat(arr2).filter(item => !(arr1.indexOf(item) >= 0 && arr2.indexOf(item) >= 0));` – Jayce444 Jan 22 '20 at 02:23
  • this is not duplicate of https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items , OP is just intrested to remove entries which are duplicate on 2 arrays – sumit Jan 22 '20 at 10:41

3 Answers3

1

You can achieve it in this simple way

let arr1=['a', 'b', 'c', 'd'];
let arr2=['a', 'e', 'd', 'f', 'p'];

var getInA_Not_InB = (a, b) => { return a.filter(v => b.indexOf(v) == -1)};
var result = getInA_Not_InB(arr1, arr2)
                                       .concat(getInA_Not_InB(arr2, arr1));
console.log(result);
Nguyễn Văn Phong
  • 11,572
  • 15
  • 21
  • 43
0

You can try:

let arr1 = ['a', 'b', 'c', 'd'];
let arr2 = ['a', 'e', 'd', 'f', 'p'];

let arr3 = [...findDifference(arr1, arr2), ...findDifference(arr2, arr1)];

console.log(arr3);

/* Find all elements in array1 that are not in array2 */
function findDifference(array1, array2) {
    return array1.filter(element => !array2.includes(element));
}
Andrew Bui
  • 161
  • 3
0

Another way is to merge 2 array and count frequency and filter the elements with frequency 1 , you dont need to worry about finding difference between 2 array separately and concatenate them

const arr1=['a', 'b', 'c', 'd']
const arr2=['a', 'e', 'd', 'f', 'p']
let merged=[...arr1,...arr2]
const mapped = [...new Set(merged)].filter(a => merged.filter(a1 => a1 === a).length ===1 );
console.log(mapped);
sumit
  • 13,148
  • 10
  • 57
  • 103