Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to splice duplicate item in array 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
