Remove duplicate from sorted array

Remove duplicate from sorted array

One of the Most frequently asked javascript DS Algo Question Remove Duplicate from sorted Array in Technical Round. We Can Solve this problem in a different way such as by using Object Method and many more methods, we can see below all the methods...


There are some test cases, which helps us to understand the question:-

// first test case
input = [1,1,2]
   output = [1,2]

// second test case 
 input = [1,2,2,3,4,4,45,88,88]
    output = [1,2,3,4,45,88]

1. Remove duplicate by using the inbuilt method

=> In this method, we are using the spread method and also the new Set method.

let arr = [1, 1, 3, 3, 5];

let remove_duplicates= [...new Set(arr)];
console.log(remove_duplicates)

// OUTPUT :-
// [1,3,5]

2. Remove Duplicate by using Object method

=>In this method, We put all the duplicates in the object and lastly push in the new array.

function removeDuplicatefromArray(data) {


  let n = data.length;

  let result = [];
  if (n == 0 || n == 1) {
    return n;
  }
  let obj = {};

  for (let i = 0; i < n; i++) {
    if (!obj[data[i]]) {
      obj[data[i]] = true;
      result.push(data[i]);
    }
  }
  return result;
}

let arr = [4,5,8,8,8,9,9,12,55,88,99,99,101]

let final = removeDuplicatefromArray(arr)
console.log(final);