
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements