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' ] ]