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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>Suppose we have an array of arrays like this &minus;</p><pre class="result notranslate">const arr = [ &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Serta&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Serta&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Simmons&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Simmons&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Simmons&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Simmons&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;] ];</pre><p>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.</p><p>The code for this will be &minus;</p><pre class="prettyprint notranslate">const arr = [ &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Serta&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Serta&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Simmons&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Simmons&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Simmons&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;], &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; &quot;Simmons&quot;, &nbsp; &nbsp; &nbsp; &quot;Black Friday&quot; &nbsp; &nbsp;] ]; const filterCommon = arr =&gt; { &nbsp; &nbsp;const map = Object.create(null); &nbsp; &nbsp;let res = []; &nbsp; &nbsp;res = arr.filter(el =&gt; { &nbsp; &nbsp; &nbsp; const str = JSON.stringify(el); &nbsp; &nbsp; &nbsp; const bool = !map[str]; &nbsp; &nbsp; &nbsp; map[str] = true; &nbsp; &nbsp; &nbsp; return bool; &nbsp; &nbsp;}); &nbsp; &nbsp;return res; }; console.log(filterCommon(arr));</pre><h2>Output</h2><p>The output in the console &minus;</p><pre class="result notranslate">[ [ &#39;Serta&#39;, &#39;Black Friday&#39; ], [ &#39;Simmons&#39;, &#39;Black Friday&#39; ] ]</pre>
raja
Updated on 12-Oct-2020 11:25:35

Advertisements