3. Remove Duplicate Members of an Array
Define the Problem
The problem is pretty straightforward (remove duplicate members of an array) but we're going to have Jonathan clear up any doubts or assumptions.
Jonathan: I'll be using JavaScript to solve the problem, and I'll assume any data type is in the array. I'll also assume a new array is being returned.
Interviewer: Okay.
Think
Jonathan thinks about the problem for a bit. He's already starting to come up with some solutions and writes out some of his thoughts on the board. Here's his pseudocode:
// Create an array to store values that have been parsed over at least once in a loop; "duplicates array"
/* Generate a loop of some kind that will go through all of the elements in the array. Elements parsed through
only once will be stored in the duplicates array. */
/* Loop will have conditional statement to return new array of elements only if they aren't within
duplicates array. */
// return unique elements array.
// Log unique elements
Write Code and Syntax
Now that the hard part is done, Jonathan just needs to write out the syntax to fill in the pseudocode. As Jonathan writes the code, he explains the syntax.
// Create an array to store values that have been parsed over at least once in a loop; "uniques array"
var uniqueArr = [];
/* Generate a loop of some kind that will go through all of the elements in the array. Elements parsed through
only once will be stored in the uniques array. */
function removeDuplicates(arr) {
/* Loop will have conditional statement to return new array of elements only if they aren't within
uniques array. */
return arr.filter(function(element, index){
if (uniqueArr.indexOf(element) == -1) {
uniqueArr.push(element);
// return unique elements
return element;
}
});
}
// Log unique elements array
console.log(removeDuplicates(["test", "test", true, false, true, 1, 1, 3, -1, 5, 5]);
Jonathan: I first started thinking about how I would store unique elements into an array. The easiest thing to do would be to use nested for loops, but I know that would have been inefficient.
I started thinking about methods in JavaScript that work on arrays and can help filter out elements efficiently. I chose the filter method and then combined it with a conditional statement and an indexOf method to only push elements that are unique into the uniqueArr.
Finally, I tested out the function using a simple array of strings, Boolean values, and numbers. The function can't handle deeply nested objects, but it's able to handle simple data types."
Interviewer: Okay.