Skip to content

Commit 595b53f

Browse files
remove duplicates from array/string
1 parent fe7ba4f commit 595b53f

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# 0027 removeDuplicates ( L-B )
2+
3+
## Problem
4+
Write a function that removes duplicate values from the given input.
5+
- If the input is an array, return a new array with unique values.
6+
- If the input is a string, return a new string with duplicate characters removed.
7+
- The original order must be preserved.
8+
9+
## Solution
10+
```js
11+
function removeDuplicates(input) {
12+
let unique = [];
13+
for (let i = 0; i < input.length; i++) {
14+
if (!unique.includes(input[i])) {
15+
unique.push(input[i]);
16+
}
17+
}
18+
if(typeof(input) === "string"){
19+
unique = unique.toString().replace(/,/g, '');
20+
}
21+
console.log(unique);
22+
return unique;
23+
}
24+
```
25+
26+
## Test Cases
27+
```js
28+
removeDuplicates([2, 4, 8, 4, 2, 6, 9, 2, 6, 8, 10]);
29+
// Output: [2, 4, 8, 6, 9, 10]
30+
31+
removeDuplicates([1, 1, 1, 4, 0, 6, -2, 2, 6, 7, 10]);
32+
// Output: [1, 4, 0, 6, -2, 2, 7, 10]
33+
34+
removeDuplicates("zoom");
35+
// Output: "zom"
36+
37+
removeDuplicates("hello world");
38+
// Output: "helo wrd"
39+
```
40+
41+
## How it works
42+
- Create an empty array called unique
43+
- Loop through each character or element in the input
44+
- Check if the current value already exists in unique
45+
- If it does not exist, we add it to unique
46+
- After the loop:
47+
- If the input is a string, we convert the array into a string
48+
- Remove commas using replace
49+
- Finally, return the result
50+
51+
## References
52+
- [MDN – Array.prototype.includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
53+
- [MDN – typeof operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
54+
55+
56+
## Problem Added By
57+
- [GitHub](https://github.com/rimsha-shoukat)
58+
59+
## Contributing
60+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
61+
62+
Please make sure to update tests as appropriate.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function removeDuplicates(input) {
2+
let unique = [];
3+
for (let i = 0; i < input.length; i++) {
4+
if (!unique.includes(input[i])) {
5+
unique.push(input[i]);
6+
}
7+
}
8+
if(typeof(input) === "string"){
9+
unique = unique.toString().replace(/,/g, '');
10+
}
11+
console.log(unique);
12+
return unique;
13+
}
14+
15+
removeDuplicates([2, 4, 8, 4, 2, 6, 9, 2, 6, 8, 10]);
16+
removeDuplicates([1, 1, 1, 4, 0, 6, -2, 2, 6, 7, 10]);
17+
removeDuplicates("zoom");
18+
removeDuplicates("hello world");

0 commit comments

Comments
 (0)