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:
javascriptfunction 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.