- 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
Get unique item from two different array in JavaScript
We are required to make a function that accepts an array of arrays, and returns a new array with all elements present in the original array of arrays but remove the duplicate items.
For example − If the input is −
const arr = [ [12, 45, 65, 76, 76, 87, 98], [54, 65, 98, 23, 78, 9, 1, 3], [87, 98, 3, 2, 123, 877, 22, 5, 23, 67] ];
Then the output should be single array of unique elements like this −
[ 12, 45, 54, 78, 9, 1, 2, 123, 877, 22, 5, 67 ]
Example
const arr = [ [12, 45, 65, 76, 76, 87, 98], [54, 65, 98, 23, 78, 9, 1, 3], [87, 98, 3, 2, 123, 877, 22, 5, 23, 67] ]; const getUnique = (arr) => { const newArray = []; arr.forEach((el) => newArray.push(...el)); return newArray.filter((item, index) => { return newArray.indexOf(item) === newArray.lastIndexOf(item); }); }; console.log(getUnique(arr));
Output
The output in the console will be −
[ 12, 45, 54, 78, 9, 1, 2, 123, 877, 22, 5, 67 ]
Advertisements