-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove_Duplicate.js
More file actions
59 lines (43 loc) · 1.54 KB
/
Remove_Duplicate.js
File metadata and controls
59 lines (43 loc) · 1.54 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
57
58
59
/* ----------------------------------------------------------------------------------------
Define a function that removes duplicates from an array of non negative numbers and
returns it as a result.
The order of the sequence has to stay the same.
Examples:
Input -> Output
[1, 1, 2] -> [1, 2]
[1, 2, 1, 1, 3, 2] -> [1, 2, 3]
---------------------------------------------------------------------------------------- */
/*
Array.prototype.filter(): creates a shallow copy of a portion of a given array
filtered down to just the elements from the given array
that pass the test implemented by the provided function
Array.prototype.indexOf(): returns the first index at which a given element can be
found in the array, or -1 if it is not present.
*/
function distinct(a) {
return a.filter((element, index) => {
return a.indexOf(element) === index;
});
}
/*
Alternative solution:
new Set(): use the Set class constructor passing the array as an iterable parameter
in order to create a set of unique elements
*/
function distinct(a) {
return [...new Set(a)];
}
/*
Alternative solution:
Array.prototype.includes(): check if the parameter element is included in the array
Array.prototype.push(): pushes a new element in the array
*/
function distinct(arr) {
let res = [];
for (let i of arr) {
if (!res.includes(i)) {
res.push(i);
}
}
return res;
}