
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
Splice Duplicate Items in Array using JavaScript
We have an array of Number / String literals that contain some duplicate values, we have to remove these values from the array without creating a new array or storing the duplicate values anywhere else.
We will use the Array.prototype.splice() method to remove entries inplace, and we will take help of Array.prototype.indexOf() and Array.prototype.lastIndexOf() method to determine the duplicacy of any element.
Example
const arr = [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5]; arr.forEach((el, ind, array) => { if(array.indexOf(el) !== array.lastIndexOf(el)){ array.splice(ind, 1); } }); console.log(arr);
Output
The output in the console will be −
[ 4, 1, 5, 2, 6, 8, 7 ]
Advertisements