-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-5_Remove_Duplicates_from_an_Array.js
More file actions
53 lines (45 loc) · 1.98 KB
/
Problem-5_Remove_Duplicates_from_an_Array.js
File metadata and controls
53 lines (45 loc) · 1.98 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
// Problem-5_Remove_Duplicates_from_an_Array with Solution, Explanation, Verification, and Execution:
// To remove duplicates from an array, we can implement the Solution like below:
// -------------------------------------------------------------------
function removeDuplicates(arr) {
let unique = [];
for (let num of arr) {
let isDuplicate = false;
for (let existing of unique) {
if (num === existing) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
unique.push(num);
}
}
return unique;
}
// Explanation:
// ---------------
// The function creates an empty array to store unique elements. It iterates over each number in the input array using a for-of loop. For each number, it checks against the unique array with a nested loop to see if it already exists; if found, a flag is set to true. If the flag remains false after the check, the number is added to the unique array. This nested iteration approach manually detects and skips duplicates, preserving order without using sets or advanced filtering.
// Verification:
// ----------------
// function removeDuplicates(arr=[1, 2, 2, 3, 4, 4]) {
// let unique = [];
// for (let num of arr) {
// let isDuplicate = false;
// for (let existing of unique) {
// if (num === existing) {
// isDuplicate = true;
// break;
// }
// }
// if (!isDuplicate) {
// unique.push(num);
// }
// }
// return unique;
// }
// console.log(removeDuplicates([1, 2, 2, 3, 4, 4]));
// Execution of the above code block in IDE environment with node.js installed:
// ----------------------------------------------------------------------
// Input (In the directory in IDE environment with node.js installed): 'node Problem-5_Remove_Duplicates_from_an_Array.js'
// Output (In the directory in IDE environment with node.js installed): [1, 2, 3, 4]