Share
Explore

JavaScript Code Drills Exercise Series B


Write a function called removeDuplicates that takes an array of strings as an argument and returns a new array with all duplicates removed.
For example, if the input array is ["apple", "banana", "cherry", "banana", "apple"], the function should return the array ["apple", "banana", "cherry"].
Your implementation should preserve the order of the elements in the input array and should not modify the input array. If the input array contains only unique elements, the function should return a new array with the same elements.
Here's an example of how the function should be used:

let input = ["apple", "banana", "cherry", "banana", "apple"];
let output = removeDuplicates(input);
console.log(output); // should print ["apple", "banana", "cherry"]

You can use a JavaScript object to keep track of the unique elements that have been encountered while iterating over the input array. Alternatively, you can use the indexOf method to check whether an element has already been seen while iterating over the input array.

function removeDuplicates(arr) {

let seen = {};

let result = [];

for (let i = 0; i < arr.length; i++) {

let element = arr[i];

if (!seen[element]) {

seen[element] = true;

result.push(element);

}

}

return result;

}


In this solution, we use an object called seen to keep track of the unique elements that have been seen while iterating over the input array.
We initialize an empty object at the beginning of the function, and then for each element in the input array, we check whether it has been seen before.
If the element has not been seen before, we add it to the result array and set its value in the seen object to true.
The result array contains all the unique elements in the order in which they appear in the input array, and the function returns this array at the end.
Here's an example of how the function can be used:
let input = ["apple", "banana", "cherry", "banana", "apple"];
let output = removeDuplicates(input);
console.log(output); // should print ["apple", "banana", "cherry"]

The output of the above code should be ["apple", "banana", "cherry"].

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.