Remove All Instances of Repeated Elements from Array in JavaScript



We are required to write a function that takes in an array and returns a new array that have all duplicate values removed from it. The values that appeared more than once in the original array should not even appear for once in the new array.

For example, if the input is −

const arr = [763,55,43,22,32,43,763,43];

The output should be −

const output = [55, 22, 32];

Array.prototype.indexOf(): It returns the index of first occurrence of searched string if it exists, otherwise -1.

Array.prototype.lastIndexOf(): It returns the index of last occurrence of searched string if it exists, otherwise -1.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = [763,55,43,22,32,43,763,43];
const deleteDuplicate = (arr) => {
   const output = arr.filter((item, index, array) => {
      return array.indexOf(item) === array.lastIndexOf(item);
   });
   return output;
};
console.log(deleteDuplicate(arr));

Output

The output in the console will be −

[ 55, 22, 32 ]
Updated on: 2020-10-20T11:46:45+05:30

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements