- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract unique values from an array - JavaScript
Suppose we have an array that contains duplicate elements like this −
const arr = [1,1,2,2,3,4,4,5];
We are required to write a JavaScript function that takes in one such array and returns a new array. The array should only contain the elements that only appear once in the original array.
Example
Following is the code −
const arr = [1,1,2,2,3,4,4,5]; const extractUnique = arr => { const res = []; for(let i = 0; i < arr.length; i++){ if(arr.lastIndexOf(arr[i]) !== arr.indexOf(arr[i])){ continue; }; res.push(arr[i]); }; return res; }; console.log(extractUnique(arr));
Output
This will produce the following output in console −
[ 3, 5 ]
Advertisements