skip to Main Content

As per the title, in one of the interview I got the above problem to solve, but i confused to get the answer. Can any one give me the solution please.

Thanks in Advance!

I am expecting solution as per the requirement without using any built in methods available in JavaScript.

2

Answers


  1. You would use a for loop.

    The removeDuplicates function takes an array as input and creates a new array (uniqueArray) to store the unique elements. It then iterates through each element in the input array using a for loop.

    For each element in the input array, it checks whether that element is already present in the uniqueArray using the indexOf method. If the element is not found (i.e., indexOf returns -1), it means the element is unique, and it is added to the uniqueArray using the push method.

    See below example:

    function removeDuplicates(array) {
      var uniqueArray = [];
      for (var i = 0; i < array.length; i++) {
        if (uniqueArray.indexOf(array[i]) === -1) {
          uniqueArray.push(array[i]);
        }
      }
      return uniqueArray;
    }
    
    var originalArray = [1, 2, 2, 3, 4, 4, 5];
    var newArray = removeDuplicates(originalArray);
    
    console.log(newArray); // Output: [1, 2, 3, 4, 5]
    
    Login or Signup to reply.
  2. You can remove duplicate elements from an array in JavaScript without using built-in array methods by creating a new array and iterating through the original array. Here’s one way to achieve this:

    let removeDuplicates=(arr)=> {
      let uniqueArray = [];
    
      for (let i = 0; i < arr.length; i++) {
        if (uniqueArray.indexOf(arr[i]) === -1) {
          uniqueArray.push(arr[i]);
        }
      }
    
      return uniqueArray;
    }
    
    // Example usage:
    const originalArray = [1, 2, 3, 4, 1, 2, 5];
    const newArray = removeDuplicates(originalArray);
    
    console.log(newArray); // Output: [1, 2, 3, 4, 5]

    In the above example, the removeDuplicates function iterates through the original array (arr) and checks whether each element is already present in the uniqueArray using the indexOf method. If the element is not found in uniqueArray (i.e., indexOf returns -1), it is added to the uniqueArray. This way, duplicates are not included in the new array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search