-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithm2.html
69 lines (47 loc) · 1.61 KB
/
algorithm2.html
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<!DOCTYPE html>
<html>
<body>
<script>
//https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays
//Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
/* solution #1
function diffArray(arr1, arr2) {
var newArr = [];
for (var i=0; i<arr1.length; i++) {
if (arr2.indexOf(arr1[i]) < 0) {
newArr.push(arr1[i]);
}
}
for (var i=0; i<arr2.length; i++) {
if (arr1.indexOf(arr2[i]) < 0) {
newArr.push(arr2[i]);
}
}
return newArr;
}
*/
function diffArray(arr1, arr2) {
return arr1.filter(x => (arr2.indexOf(x) < 0)).concat(arr2.filter(x => (arr1.indexOf(x) < 0)));
}
/*function counters(arr) {
var counters = {};
for (var i=0; i<arr.length; i++) {
if (counters[arr[i]] == undefined) {
counters[arr[i]] = 1;
} else {
counters[arr[i]] = counters[arr[i]] + 1;
}
}
return counters;
}
function diffArray(arr1, arr2) {
var newArr = arr1.concat(arr2);
return Object.entries(counters(newArr)).filter(([_,v]) => (v<2)).map(([key,_])=>key);
}
*/
//Tests
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
console.log(diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]));
</script>
</body>
</html>