-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithm10.html
55 lines (41 loc) · 1.5 KB
/
algorithm10.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
<!DOCTYPE html>
<html>
<body>
<script>
//https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union
//Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.
//The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.
function uniteUnique(...arr) {
// 1. convert all arrays to the string
// var newArr = arr.toString().split(",");
// var numbArr = newArr.map(item => Number(item));
var newArr = arr.reduce((item1,item2) => [...item1, ...item2]);
// 2. compare them and find duplicates
var counters = {};
var result = [];
for (var i=0; i<newArr.length; i++)
{
if (!counters[newArr[i]]) {
counters[newArr[i]] = true;
result.push(newArr[i]);
}
}
return result;
// newArr = new Set(newArr);
// newArr = Array.from(newArr);
//return newArr;
}
//Solution #2
// function uniteUnique(...arrays) {
// //make an array out of the given arrays and flatten it (using the spread operator)
// const flatArray = [].concat(...arrays);
// // create a Set which clears any duplicates since it's a regulat set and not a multiset
// return [...new Set(flatArray)];
// }
//tests
console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));
console.log(uniteUnique([1, 2, 3], [5, 2, 1]));
console.log(uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]));
</script>
</body>
</html>