Write a function that removes duplicates from an array using Javascript.

 You can create a function in JavaScript to remove duplicates from an array by iterating through the array and keeping track of unique elements encountered so far. Here's one way to implement this:

javascript
function removeDuplicates(arr) { 
// Create an empty object to store unique elements 
var uniqueElements = {}; 
// Create an array to store the final result without duplicates 
var result = []; 
// Iterate through each element in the array 
for (var i = 0; i < arr.length; i++) { 
// Check if the current element is not already in the uniqueElements object 
if (!uniqueElements[arr[i]]) { 
// Add the current element to the uniqueElements object 
 uniqueElements[arr[i]] = true
// Add the current element to the result array result.push(arr[i]); 
 } 
 } 
// Return the array with duplicates removed 
return result; } 
// Example usage: 
var arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5]; 
var arrayWithoutDuplicates = removeDuplicates(arrayWithDuplicates); 
console.log("Array without duplicates:", arrayWithoutDuplicates); 
// Output: [1, 2, 3, 4, 5]

This function removeDuplicates takes an array arr as input and returns a new array containing only the unique elements from the input array. It uses an object uniqueElements to keep track of unique elements encountered so far and builds the result array by iterating through the input array. Finally, it returns the result array with duplicates removed.

Sudhir Kumar

i am blogger | Vloggger | Digital Marketer having work experience of more than 5 years.

Post a Comment

Previous Post Next Post