Remove duplicate items from an array with a custom function in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals. If an element appears for more than once in the array, the function remove all its instances from the array.

For example −

If the input array is −

const arr = [1,2,3,4,4,5,5];

Then the output should be −

const output = [1, 2, 3];

Example

const arr = [1, 2, 3, 4, 4, 5, 5];
const removeAll = (arr = [], val) => {
   while(arr.includes(val)){
      const index = arr.indexOf(val);
      arr.splice(index, 1);
   };
};
const eradicateDuplicates = (arr = []) => {
   for(let i = 0; i < arr.length; ){
      const el = arr[i];
      if(arr.indexOf(el) === arr.lastIndexOf(el)){
         i++;
         continue;
      };
      removeAll(arr, el);
   };
};
eradicateDuplicates(arr);
console.log(arr);

Output

And the output in the console will be −

[1, 2, 3]
raja
Published on 25-Nov-2020 12:35:06
Advertisements