Skip to content

Commit 3e15016

Browse files
committed
remove_duplicates javascript
1 parent 94e0c5f commit 3e15016

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
remove duplicates from an array
3+
4+
could have 0 elements
5+
6+
could be any type of value
7+
8+
*/
9+
10+
function removeDuplicates(arr){
11+
12+
if(arr.length <= 1) return arr;
13+
14+
var table = {};
15+
var output = [];
16+
var hash_key;
17+
18+
for(var i = 0; i < arr.length; i++){
19+
hash_key = JSON.stringify(arr[i]);
20+
21+
if(!table[hash_key]){
22+
output.push(arr[i]);
23+
}
24+
25+
table[hash_key] = true;
26+
}
27+
28+
return output;
29+
}
30+
31+
module.exports = removeDuplicates;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
var assert = require('assert');
2+
var removeDuplicates = require('../../interview_questions/remove_duplicates.js');
3+
4+
describe('Remove Duplicates', function() {
5+
6+
describe('should work with arrays', function() {
7+
8+
it('that are empty', function() {
9+
assert.deepEqual(removeDuplicates([]), []);
10+
});
11+
12+
it('with no duplicates', function() {
13+
assert.deepEqual(removeDuplicates([1,2]), [1,2]);
14+
});
15+
16+
it('that have duplicates', function() {
17+
assert.deepEqual(removeDuplicates([3,3,3]), [3]);
18+
});
19+
20+
it('that contain objects', function() {
21+
22+
var Person = function(name) {
23+
this.name = name;
24+
};
25+
26+
Person.prototype = {
27+
name: null
28+
};
29+
30+
var albert = new Person('Albert');
31+
var bob = new Person('Bob');
32+
var bobAgain = new Person('Bob');
33+
34+
var input = [albert,bob, bobAgain];
35+
36+
assert.deepEqual(removeDuplicates(input), [albert,bob]);
37+
});
38+
39+
});
40+
41+
});

0 commit comments

Comments
 (0)