
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter Out Common Array in Array of Arrays in JavaScript
Suppose we have an array of arrays like this −
const arr = [ [ "Serta", "Black Friday" ], [ "Serta", "Black Friday" ], [ "Simmons", "Black Friday" ], [ "Simmons", "Black Friday" ], [ "Simmons", "Black Friday" ], [ "Simmons", "Black Friday" ] ];
We are required to write a JavaScript function that takes in one such array. And the function should return a new array that contains all the unique subarrays from the original array.
The code for this will be −
const arr = [ [ "Serta", "Black Friday" ], [ "Serta", "Black Friday" ], [ "Simmons", "Black Friday" ], [ "Simmons", "Black Friday" ], [ "Simmons", "Black Friday" ], [ "Simmons", "Black Friday" ] ]; const filterCommon = arr => { const map = Object.create(null); let res = []; res = arr.filter(el => { const str = JSON.stringify(el); const bool = !map[str]; map[str] = true; return bool; }); return res; }; console.log(filterCommon(arr));
Output
The output in the console −
[ [ 'Serta', 'Black Friday' ], [ 'Simmons', 'Black Friday' ] ]
Advertisements