-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove-duplicates-from-array.js
More file actions
56 lines (43 loc) · 1.02 KB
/
Copy pathremove-duplicates-from-array.js
File metadata and controls
56 lines (43 loc) · 1.02 KB
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
/**
* * Remove Duplicates from an Array
*
* @param {number[]} array
* @return {number[]}
*/
// TIP: In-place solution
// O(n) time | O(n) space
function removeDuplicates(array) {
let hash = {}
for (let i = 0; i < array.length; i++) {
if (!hash[array[i]]) {
hash[array[i]] = true
} else {
array.splice(i, 1)
}
}
return array
}
// -----------------------------
// SOLUTION 2
// TIP: Built-in solution
// O(n) time | O(n) space
function removeDuplicates2(array) {
return [...new Set(array)]
}
// -----------------------------
// SOLUTION 3
// O(n) time | O(n) space
function removeDuplicates3(array) {
let result = []
for (let i = 0; i < array.length; i++) {
if (!result.includes(array[i])) {
result.push(array[i])
}
}
return result
}
// -----------------------------
// TESTS
console.log(removeDuplicates([1, 2, 3, 2, 4, 1])) // [1, 2, 3, 4]
console.log(removeDuplicates2([1, 2, 3, 2, 4, 1])) // [1, 2, 3, 4]
console.log(removeDuplicates3([1, 2, 3, 2, 4, 1])) // [1, 2, 3, 4]