Remove Duplicates From an Array

JavaScript

Function to remove duplicates from an array:

Create a function in JavaScript to find the largest number in an array by iterating through the array and keeping track of the maximum value found. Here's how you can implement it:

js Copy Code
function removeDuplicates(arr) {
  let uniqueArray = [];
  
  // Iterate through the original array
  for (let i = 0; i < arr.length; i++) {
    // If the element is not already in the uniqueArray, add it
    if (uniqueArray.indexOf(arr[i]) === -1) {
      uniqueArray.push(arr[i]);
    }
  }
  
  return uniqueArray;
}

// Example usage:
const arrayWithDuplicates = [1, 2, 2, 3, 4, 4, 5];
const arrayWithoutDuplicates = removeDuplicates(arrayWithDuplicates);
console.log("Array without duplicates:", arrayWithoutDuplicates);
Output:
Array without duplicates: [ 1, 2, 3, 4, 5 ]

Explanation:

1. We initialize an empty array 'uniqueArray' to store unique elements.

2. We iterate through the original array.

3. For each element, we check if it's already in 'uniqueArray' using the 'indexOf()' method.

4. If the element is not found ('indexOf()' returns -1), we add it to 'uniqueArray'.

5. Finally, we return 'uniqueArray' containing only the unique elements.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.