Syntax error How to filter out common array in array of arrays in JavaScript

How to 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' ] ]
Updated on: 2020-10-12T11:25:35+05:30

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements