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
Program to pick out duplicate only once - JavaScript
We have an array of literals that contains some duplicate values appearing for many times like this −
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
We are required to write a JavaScript function that takes in this array and pick out all the duplicate entries from the original array and only once.
So, for the above array, the output should be −
const output = [1, 4, 3, 2];
Example
Let’s write the code for this function −
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
const pickDuplicate = arr => {
const res = [];
for(let i = 0; i < arr.length; i++){
if(arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])){
if(!res.includes(arr[i])){
res.push(arr[i]);
};
};
};
return res;
};
console.log(pickDuplicate(arr));
Output
The output in the console: −
[1, 4, 3, 2]
Advertisements
