In: Computer Science
This all has to be in javascript
A common way to remove duplicates from an array is to convert it to a set and then convert it back to an array. We will do that here. Please use these variables and data structures:
var input = [3, 4, 2, 2, 4, 5, 3, 1, 3, 6];
var set = new Set();
1. Get each element from the input array and add it to the set.
2. Get the elements from the set, put them back into an array, and print them. Does it work correctly? I.e., have the duplicates been removed? HINT: Set has an operation that is very useful here.
3. Finish the function below that checks whether an array has duplicates. You must to use a Set in the implementation of this function. HINT: the return value of add() (true/false) indicates whether the element already exists in the set.
function hasDuplicates(arr) {
var set = new Set();
(hint: use a loop)
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function removeDuplicates(arr) {
var set=new Set();
for(i=0;i<arr.length;i++)
set.add(arr[i]);
return Array.from(set);
}
function hasDuplicates(arr) {
var set = new Set();
for(i=0;i<arr.length;i++)
if(!set.has(arr[i]))
return
true;
return false;
}
function myFunction() {
var arr=[1,2,3,4,1,2,3,4];
alert("has duplicates? "+hasDuplicates(arr));
alert("Before Removing Duplicates: "+arr+"\nAfter
removing duplicates: "+removeDuplicates(arr));
}
</script>
</body>
</html>
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME