-
Notifications
You must be signed in to change notification settings - Fork 4
/
symmetric-difference.js
54 lines (41 loc) · 1.15 KB
/
symmetric-difference.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
* Algorithm that returns an array of symmetric difference of provided arrays
*/
function sym(args) {
// storing arguments in an array
const arr = Object.values(arguments);
// function for finding symmetric diff between two arrays
function diff(a, b) {
// converting arrays to set to remove duplicate values
let setA = new Set(a);
let setB = new Set(b);
let arrA = [];
let arrB = [];
// object for storing number of times a value occurs
let valueMap = {};
// result => for storing symmetric diff
let result = [];
// converting set back to array
for (let i of setA) {
arrA.push(i);
}
for (let i of setB) {
arrB.push(i);
}
// checking occurrence of a value
arrA.map(x => {
valueMap[x] ? valueMap[x]++ : (valueMap[x] = 1);
});
arrB.map(x => {
valueMap[x] ? valueMap[x]++ : (valueMap[x] = 1);
});
// storing valid values to result array
for (let i in valueMap) {
valueMap[i] === 1 ? result.push(parseInt(i)) : false;
}
return result;
}
// reducing arr to get the final result
return arr.reduce(diff);
}
module.exports = sym;