-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution02.txt
More file actions
73 lines (57 loc) · 2.11 KB
/
solution02.txt
File metadata and controls
73 lines (57 loc) · 2.11 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
Question #2: Array Deduping
Prompt: Write an algorithm that removes duplicates from an array. Do not use a function like filter() to solve this. Once you have solved the problem, demonstrate how it can be solved with filter(). Solve the problem with and without recursion.
Questions for interviewers:
- Will numbers always be passed as integers? (no numbers as strings?)
Possible edge cases:
- An empty array
Example Inputs/Outputs:
Input: [7, 9, "hi", 12, "hi", 7, 53]
Output: [7, 9, "hi", 12, 53]
Input: [3, 3, 3, 3]
Output: [3]
Input: [3, "3"]
Output: [3, "3"] ? // technically, these elements are not duplicates as they are different datatypes
Input: []
Output: []
Solution without recursion or filter:
1. Copy the original array using spread syntax
2. Use the Set object to create a new array of unique elements
let array = [7, 9, "hi", 12, "hi", 7, 53];
function removeDupes(array) {
let noDupes = [...new Set(array)]
return noDupes;
}
// using a foreach
function removeDupes(array) {
let noDupes = [];
array.forEach(function(element) {
if(!noDupes.includes(element)) {
noDupes.push(element);
}
});
}
Solution with filter:
1. Compare all elements in array to see if the index is the first time that element appears
2. Create new array with unique elements
let array = [7, 9, "hi", 12, "hi", 7, 53];
function removeDupes(array) {
let uniqueArray = array.filter(function(element, index) {
return array.indexOf(element) === index;
});
return uniqueArray;
}
Solution with recursion:
Write a function that takes an array, if that array's length is 0, break out of the recursive loop.
Create a constant array to
const array = [7, 9, "hi", 12, "hi", 7, 53];
const removeDupes = (array) => {
if (array.length === 0) {
return array.concat([]);
}
const uniqueArray = array.slice(0, -1); // create new array based off of original
if (uniqueArray.includes(array[array.length - 1])) { // compare the arrays
return removeDupes(uniqueArray) // if match is found, return and call the function again
} else {
return removeDupes(uniqueArray).concat(array[array.length - 1]) // if no match is found, search the next index
}
}