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
-
Economics & Finance
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 ]
Using indexOf and lastIndexOf
This approach flattens the arrays and filters out elements that appear more than once by comparing their first and last occurrence positions.
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));
[ 12, 45, 54, 78, 9, 1, 2, 123, 877, 22, 5, 67 ]
Using Set and Filter
This method uses a Set to track seen elements and filters out duplicates during the flattening process.
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 getUniqueWithSet = (arr) => {
const flattened = arr.flat();
const counts = {};
// Count occurrences
flattened.forEach(item => {
counts[item] = (counts[item] || 0) + 1;
});
// Return items that appear only once
return flattened.filter((item, index) => {
return counts[item] === 1 && flattened.indexOf(item) === index;
});
};
console.log(getUniqueWithSet(arr));
[ 12, 45, 54, 78, 9, 1, 2, 123, 877, 22, 5, 67 ]
Comparison
| Method | Time Complexity | Readability |
|---|---|---|
| indexOf/lastIndexOf | O(n²) | Good |
| Set with counting | O(n) | Better |
Conclusion
Both methods effectively extract unique elements from nested arrays. The Set-based approach offers better performance for large datasets, while the indexOf method is more straightforward to understand.
