
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Completely removing duplicate items from an 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 = [23,545,43,232,32,43,23,43];
The output should be −
const output = [545, 232, 32];
Understanding the difference −
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.
Both methods start from left to right.
Both methods start from 0 if second argument is undefined, other start from the second argument if it’s a number.
So the vital point here is, if in an array, the indexOf() and lastIndexOf() method point to the same index, we can sure that it only exists once, so we will use this finding in our code.
The full code for the function will be −
Example
const arr = [23,545,43,232,32,43,23,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 −
[ 545, 232, 32 ]
- Related Questions & Answers
- Removing duplicate objects from array in JavaScript
- Removing duplicate elements from an array in PHP
- Remove duplicate items from an array with a custom function in JavaScript
- Find the least duplicate items in an array JavaScript
- Removing an element from an Array in Javascript
- Removing duplicate values in a twodimensional array in JavaScript
- Remove duplicate items from an ArrayList in Java
- Removing Negatives from Array in JavaScript
- Removing consecutive duplicates from strings in an array using JavaScript
- Removing an element from the end of the array in Javascript
- Removing an element from the start of the array in javascript
- Return the first duplicate number from an array in JavaScript
- How to remove duplicate elements from an array in JavaScript?
- Removing redundant elements from array altogether - JavaScript
- JavaScript Algorithm - Removing Negatives from the Array